Search code examples
javafloating-pointfloating-point-conversion

Odd result From DecimalFormat Rounding Half Up


Supplying a float value of 37.35 I am getting a string of 37.3

Here is my code.

DecimalFormat format = new DecimalFormat(".0");
format.setRoundingMode(RoundingMode.HALF_UP);
return format.format(37.35f);

I would expect to receive a string of 37.4. What am I doing wrong?

I think it may be due to passing a float in however I don't have a choice as to the type of variable I receive. Even if the actual representation of the float was 37.3500221215051544 it should still be rounded up?

The whole point of formatting this value to a string is so I can pass it to BigDecimal and have exact values such as 37.4.


Solution

  • 37.35 actually closer to 37.3 then to 37.4. You can check it woth following code:

    System.out.println(37.35f-37.3f);
    System.out.println(37.4f-37.35f);
    

    in prints 0.049999237 and 0.05000305.

    With double data type the result is differrent.

    To solve this problem just add a little delta to your numbers. For exapmle, 0.01.