7

To my understanding, with half-even rounding, if the number that you are rounding on is equidistant between its neighbors (for example 4.5 if you are rounding on one after the decimal), you round the preceding number to the nearest even number.

For example, if you are rounding to 0 digits after the decimal 1.5, 3.5, 5.5, 7.5, and 9.5 will all be rounded up to 2, 4, 6, 8, and 10 respectively. This all works well and fine in netbeans, but I am running into problems when I round to 1 place after the decimal.

package foo;
import java.text.NumberFormat;

public class Foo {
    public static void main(String[] args) {
        NumberFormat formatter = NumberFormat.getNumberInstance();     
        formatter.setMaximumFractionDigits(1);
        System.out.print(formatter.format(4.45));
    }
}

run:

4.5

BUILD SUCCESSFUL (total time: 0 seconds)

I would think that this would round to 4.4

Additionally, if I use 4.55 for input into format, 4.5 is output where I expect 4.6 Is there an error with java or with my understanding?

jmj
  • 237,923
  • 42
  • 401
  • 438

2 Answers2

5

I'm not certain this is actually technically a bug.

The issue is that when you write 4.45 and the value is interpreted as a double, that is rounded to a binary fraction: a sum of multiples of powers of 2, to some precision. (That rounding itself is done with HALF_EVEN rounding, but with binary digits instead of decimal digits.)

That rounded value may be slightly above or slightly below 4.45, but NumberFormat will round the true binary value stored in the double, not the decimal value you wrote.

You can determine the true binary value you're actually getting by writing System.out.println(new BigDecimal(4.45)); When I do that, I get 4.45000000000000017763568394002504646778106689453125, which is the actual value being rounded to the nearest 0.1 -- which is definitely going to be 4.5.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

It rounds to integer, try this

    formatter.setMaximumFractionDigits(0);
    System.out.println(formatter.format(4.5));
    System.out.println(formatter.format(5.5));

output

4
6
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275