Java 四舍五入至最接近的0.05值时出现问题
已经有人问过了 一个流行的答案是使用以下公式Java 四舍五入至最接近的0.05值时出现问题,java,double,decimal,rounding,Java,Double,Decimal,Rounding,已经有人问过了 一个流行的答案是使用以下公式 Math.ceiling(myValue * 20) / 20 我需要以下输出作为相应的输入 16.489 (input) - 16.49(output) 使用上述公式 16.489*20 = 329.78 Math.ceil(329.78) = 330.0 and 330.0 /20 = 16.5 但我想要的是16.49 理想情况下,Math.ceil的内容应该是329.8 那么,我们
Math.ceiling(myValue * 20) / 20
我需要以下输出作为相应的输入
16.489 (input) - 16.49(output)
使用上述公式
16.489*20 = 329.78
Math.ceil(329.78) = 330.0
and 330.0 /20 = 16.5
但我想要的是16.49
理想情况下,Math.ceil的内容应该是329.8
那么,我们如何避开上述情况呢?还有许多其他情况与此类似。不应该用2*10乘/除,而应该用102 但是,我建议您使用
Math.round(100*a)/100.0
,或者如果需要打印,printf
或DecimalFormat
示例:
double input = 16.489;
// Math.round
System.out.println(Math.round(100 * input) / 100.0);
// Decimal format
System.out.println(new DecimalFormat("#.##").format(input));
// printf
System.out.printf("%.2f", input);
输出:
16.49
16.49
16.49
为什么不使用
格式化您的值
编辑:数学四舍五入(值*100.0)/100.0 我想这会对您有所帮助。此链接为您提供了一个关于如何将数字四舍五入到小数点后第n位的讨论 将16.489四舍五入到最接近的0.05是正确的16.5,16.45是下一个最低的可能值 所看到的行为是正确的。如果希望能够四舍五入到最接近的0.01,则
数学上限(myValue*100)/100
这将是一个更合适的解决方案。试试这个
round(16.489, 2, BigDecimal.ROUND_CEILING);
public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
这四舍五入为0.5。他需要0.05.16.49,四舍五入到最接近的0.05,为16.50;你想要一个四舍五入到最接近的0.005的值吗?这个问题数学不太好:)