Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does HALF_UP sometimes round down with double?

Tags:

java

rounding

The following code:

double doubleValue = 1713.6;
float floatValue = 1713.6f;
String fs = "%-9s : %-7s %-7s\n";
System.out.printf( fs, "", "double", "float" );

DecimalFormat format = new DecimalFormat("#0");
System.out.printf( fs, "toString", String.valueOf( doubleValue ), String.valueOf( floatValue ) );

format.setRoundingMode( RoundingMode.DOWN );
System.out.printf( fs, "DOWN", format.format( doubleValue ), format.format( floatValue ) );

format.setRoundingMode( RoundingMode.HALF_DOWN );
System.out.printf( fs, "HALF_DOWN", format.format( doubleValue ), format.format( floatValue ) );

format.setRoundingMode( RoundingMode.HALF_UP );
System.out.printf( fs, "HALF_UP", format.format( doubleValue ), format.format( floatValue ) );

format.setRoundingMode( RoundingMode.UP );
System.out.printf( fs, "UP", format.format( doubleValue ), format.format( floatValue ) );

Produces the result (live code):

          : double  float  
toString  : 1713.6  1713.6 
DOWN      : 1713    1713   
HALF_DOWN : 1714    1714   
HALF_UP   : 1713    1714   <--- notice this line
UP        : 1714    1714   

I know that certain numbers cannot be represented exactly as floating-point numbers. The actual floating-point representation for 1713.6 is 1713.5999755859375 (see this page).

But why does HALF_UP round down in this case?

Using Java 1.8u25

like image 843
GreenGiant Avatar asked Jun 04 '15 17:06

GreenGiant


People also ask

What is RoundingMode half even?

HALF_EVEN. public static final RoundingMode HALF_EVEN. Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

What is RoundingMode DOWN?

DOWN − Rounding mode to round towards zero. FLOOR − Rounding mode to round towards negative infinity. HALF_DOWN − Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.

How do you round to 2 decimal places in Java?

1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places. For DecimalFormat , the default rounding mode is RoundingMode.


2 Answers

There was a bug in Java 8 regarding the NumberFormat and RoundingMod HALF_UP see 8039915. This was fixed with 8u40 (Release Notes).

like image 85
mszalbach Avatar answered Sep 18 '22 15:09

mszalbach


Ideone is using sun-jdk-8u25 where this buggy behavior is appearing.

On Java 1.7, I'm getting HALF_UP : 1714 1714 which is right.

enum RoundingMode - Specifies a rounding behavior for numerical operations capable of discarding precision.

See Oracle javadoc: Result of rounding input to one digit with the given rounding mode[Rounding Mode Table]

like image 24
Rajesh Avatar answered Sep 18 '22 15:09

Rajesh