问题
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?
For example:
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
)
回答1:
You can use BigDecimal
as follows:
public static double roundHalfDown(double d) {
return new BigDecimal(d).setScale(0, RoundingMode.HALF_DOWN)
.doubleValue();
}
Example:
for (double d : new double[] { 2.889, 2.332, 2.5 })
System.out.printf("%.2f -> %.2f%n", d, roundHalfDown(d));
Output:
2.89 -> 3.00
2.33 -> 2.00
2.50 -> 2.00
回答2:
You can determine the fractional part fairly easily with the help of Math.floor(), then round from there based on the fractional part:
public static double roundHalfDown(double d) {
double i = Math.floor(d); // integer portion
double f = d - i; // fractional portion
// round integer portion based on fractional portion
return f <= 0.5 ? i : i + 1D;
}
回答3:
You must use BigDecimal an MathContext look here:
http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html http://docs.oracle.com/javase/6/docs/api/java/math/MathContext.html http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#ROUND_HALF_DOWN
Summary of Rounding Operations Under Different Rounding Modes
Using these classes the round works has follows
Input HALF_DOWN
5.5 5
2.5 2
1.6 2
1.1 1
1.0 1
-1.0 -1
-1.1 -1
-1.6 -2
-2.5 -2
-5.5 -5
来源:https://stackoverflow.com/questions/27450766/rounding-5-down-in-java