Tas*_*ies 19 java math rounding
我参与了我的java程序,在那里我需要四舍五入到最接近的百位并且认为可能有某种方法可以做到但我猜不是.所以我搜索网上的例子或任何答案,我还没有找到任何答案,因为所有的例子似乎都是近一百个.我只是想做这个并且向上舍入.也许有一些我忽略的简单解决方案.我已尝试过Math.ceil
其他功能,但尚未找到答案.如果有人能帮我解决这个问题,我将不胜感激.
如果我的数字是203,我希望结果四舍五入为300.你明白了.
rge*_*man 44
利用整数除法,它会截断商的小数部分.为了让它看起来像是四舍五入,先添加99.
int rounded = ((num + 99) / 100 ) * 100;
Run Code Online (Sandbox Code Playgroud)
例子:
801: ((801 + 99) / 100) * 100 ? 900 / 100 * 100 ? 9 * 100 = 900
99 : ((99 + 99) / 100) * 100 ? 198 / 100 * 100 ? 1 * 100 = 100
14 : ((14 + 99) / 100) * 100 ? 113 / 100 * 100 ? 1 * 100 = 100
452: ((452 + 99) / 100) * 100 ? 551 / 100 * 100 ? 5 * 100 = 500
203: ((203 + 99) / 100) * 100 ? 302 / 100 * 100 ? 3 * 100 = 300
200: ((200 + 99) / 100) * 100 ? 299 / 100 * 100 ? 2 * 100 = 200
Run Code Online (Sandbox Code Playgroud)
整数除法向0舍入.也就是说,在二进制数字提升(第5.6.2节)之后为操作数n和d生成的商是整数值q,其大小尽可能大,同时满足| d·q |.≤| n |.
O.C*_*.C. 10
这是一个我认为适用于任何"多个"案例的算法.让我知道你的想法.
int round (int number,int multiple){
int result = multiple;
//If not already multiple of given number
if (number % multiple != 0){
int division = (number / multiple)+1;
result = division * multiple;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
int roundUpNumberByUsingMultipleValue(double number, int multiple) {
int result = multiple;
if (number % multiple == 0) {
return (int) number;
}
// If not already multiple of given number
if (number % multiple != 0) {
int division = (int) ((number / multiple) + 1);
result = division * multiple;
}
return result;
}
Example:
System.out.println("value 1 =" + round(100.125,100));
System.out.println("value 2 =" + round(163,50));
System.out.println("value 3 =" + round(200,100));
System.out.println("value 4 =" + round(235.33333333,100));
System.out.println("value 5 =" + round(0,100));
OutPut:
value 1 =200
value 2 =200
value 3 =200
value 4 =300
value 5 =0
Run Code Online (Sandbox Code Playgroud)