Half-even rounding

In my understanding, in half rounding, if the number that you round is evenly spaced between its neighbors (for example, 4.5, if you round one after the decimal), you round the previous number to the nearest even number.

For example, if you round to 0 digits after the decimal, 1.5, 3.5, 5.5, 7.5, and 9.5 will be rounded to 2, 4, 6, 8, and 10, respectively. All this works well and perfectly in netbeans, but I run into problems when I round to 1 place after the decimal point.

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 have thought it would be round until 4.4

Also, if I use 4.55 to enter the format, 4.5 is output where I expect 4.6 Is there an error with java or with my understanding?

+6
source share
2 answers

I am not sure if this is actually a technical error.

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

This rounded value may be slightly higher or slightly lower than 4.45, but NumberFormat will round the true binary value stored in double, not the decimal value you wrote.

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

+4
source

It rounds to an integer, try

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

Output

 4 6 
+1
source

Source: https://habr.com/ru/post/980793/


All Articles