[英]Why doesn't java.math.RoundingMode come with HALF_ODD rounding?
java.math.RoundingMode comes with HALF_EVEN mode which rounds number to nearest even neighbour in the case of equidistant, but why doesn't it come with HALF_ODD mode? java.math.RoundingMode带有HALF_EVEN模式,该模式在等距的情况下将数字四舍五入到最接近的偶数邻居,但是为什么它不带有HALF_ODD模式呢?
What is the simplest way of implementing HALF_ODD rounding in Java? 在Java中实现HALF_ODD舍入的最简单方法是什么?
I hope this link can help you. 希望此链接可以为您提供帮助。
The solution proposed is: 建议的解决方案是:
public static int RoundToNearestRoundHalfToOdd(decimal value)
{
// First round half toward positive infinity. Then if the fraction
// part of the original value is 0.5 and the result of rounding is
// even, then subtract one.
var temp = (int)Math.Floor(value + 0.5m);
if (value - Math.Floor(value) == 0.5m && temp % 2 == 0)
temp -= 1;
return temp;
}
It's in C# but I guess you can convert it for Java. 它在C#中,但是我想您可以将其转换为Java。
Also to help with your task, you can see the source code for the method BigDecimal#divideAndRound in the Java SDK where everything is happening. 另外,为了帮助您完成任务,您可以在Java SDK中查看方法BigDecimal#divideAndRound的源代码,其中正在发生所有事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.