rounding .5 down in java

坚强是说给别人听的谎言 提交于 2021-01-27 13:01:29

问题


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 to 3.0
  • 2.332 is to be rounded down to 2.0
  • 2.5 is also to be rounded down to 2.0 (and NOT 3.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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!