[英]Round according to nearest decimal value - java
I have used this one我用过这个
Math.round(input * 100.0) / 100.0;
but it didn't work with my requirement.但它不符合我的要求。 I want to round into two decimal points according to nearest decimal value.
我想根据最接近的十进制值四舍五入到小数点后两位。
firstly I want to check fourth decimal value if it is 5 or above I want to add 1 into 3rd decimal value then want to check 3rd one if it is 5 or above I want to add 1 into 2nd one首先我想检查第四个十进制值是否为 5 或以上我想将 1 添加到第三个十进制值然后想检查第三个如果它是 5 或以上我想将 1 添加到第二个
ex: if I have 22.3246例如:如果我有 22.3246
refer above example number.请参阅上面的示例编号。 4th decimal no is 6. we can add 1 into 3rd decimal value.
第 4 位小数是 6。我们可以将 1 加到第 3 位小数中。
result: 22.325结果:22.325
now 3rd decimal no is 5. we can add 1 into 2nd decimal value现在第 3 位小数是 5。我们可以将 1 加到第 2 位小数中
result: 22.33结果:22.33
I want to get result 22.33我想得到结果 22.33
If you want to respect the 4th decimal digit, you can do it in this way:如果你想尊重第 4 位小数,你可以这样做:
double val = Math.round(22.3246 * 1000.0) / 1000.0;
double result = Math.round(val * 100.0) / 100.0;
System.out.println(result); // print: 22.33
You can use BigDecimal
class to accomplish this task, in combination with a scale and RoundingMode.HALF_UP
.您可以使用
BigDecimal
class 来完成此任务,并结合 scale 和RoundingMode.HALF_UP
。
Sample code:示例代码:
System.out.println(new BigDecimal("22.3246").divide(BigDecimal.ONE,3,RoundingMode.HALF_UP)
.divide(BigDecimal.ONE,2,RoundingMode.HALF_UP));
Output: Output:
22.33
According to your requirement, the greatest number to be rounded down to 22.32
is 22.3244444444...
.根据您的要求,四舍五入到
22.32
的最大数字是22.3244444444...
。 From 22.32444...4445
on, iteratively rounding digit per digit will lead to 22.33
.从
22.32444...4445
开始,每个数字的迭代舍入数字将导致22.33
。
So, you can add a bias of 0.005 - 0.0044444444
(standard rounding threshold minus your threshold), being 5/9000
and then round to the next 1/100
the standard way:因此,您可以添加
0.005 - 0.0044444444
的偏差(标准舍入阈值减去您的阈值), 5/9000
,然后以标准方式舍入到下一个1/100
:
double BIAS = 5.0 / 9000.0;
double result = Math.round((input + BIAS) * 100.0) / 100.0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.