3

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)
Piyush Vishwakarma
  • 1,816
  • 3
  • 16
  • 24
  • 1
    You mean rounded _down_. (You said up twice) – keyser Dec 12 '14 at 19:30
  • I assume you mean "round half down" as per http://en.wikipedia.org/wiki/Rounding#Round_half_down –  Dec 12 '14 at 19:35
  • What about negative numbers? Are you rounding towards zero (-2.5 rounds to -2.0) or down? (-2.5 rounds to -3.0) – Bob Kaufman Dec 12 '14 at 19:37
  • I assume you want 3.5 to round down to 3.0 also, and not to 4.0 (as "round-half-to-even" would do)? Just making sure I understand what you mean by "odd multiple". – ajb Dec 12 '14 at 19:40

3 Answers3

10

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
aioobe
  • 413,195
  • 112
  • 811
  • 826
4

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;
}
Durandal
  • 19,919
  • 4
  • 36
  • 70
2

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  
Ernesto Campohermoso
  • 7,213
  • 1
  • 40
  • 51
  • The last two results conflict with http://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html. Have you tested it? (Did this change from Java 6 to Java 8?) – ajb Dec 12 '14 at 19:47
  • The `BigDecimal.html` page that you link to says that -2.5 and -5.5 should "round down", but their definition of "round down" means toward 0. (See the definition of `ROUND_DOWN` on the same page.) So I believe the last two result should be `-2` and `-5`, even in Java 6, unless you have an implementation that's doing the wrong thing. – ajb Dec 12 '14 at 19:54
  • Sorry was m¡y mistake. Thanks ajb – Ernesto Campohermoso Dec 12 '14 at 19:56