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?
What is the simplest way of implementing HALF_ODD rounding in Java?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.