在 Java 中四舍五入 .5 [英] rounding .5 down in java
本文介绍了在 Java 中四舍五入 .5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何实现一个舍入函数,将除 0.5 或它的任何奇数倍之外的所有数字像往常一样舍入到最接近的整数?
How can you implement a rounding function which will round all numbers as usual except 0.5 or any odd multiple of it down to the nearest integer?
例如:
2.899
将四舍五入为3.0
2.332
将四舍五入为2.0
2.5
也将四舍五入为2.0
(而不是3.0
)
2.899
is to be rounded up to3.0
2.332
is to be rounded down to2.0
2.5
is also to be rounded down to2.0
(and NOT3.0
)
推荐答案
您可以使用 BigDecimal
如下:
public static double roundHalfDown(double d) {
return new BigDecimal(d).setScale(0, RoundingMode.HALF_DOWN)
.doubleValue();
}
示例:
for (double d : new double[] { 2.889, 2.332, 2.5 })
System.out.printf("%.2f -> %.2f%n", d, roundHalfDown(d));
输出:
2.89 -> 3.00
2.33 -> 2.00
2.50 -> 2.00
这篇关于在 Java 中四舍五入 .5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文