3

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.

lcnicolau
  • 3,252
  • 4
  • 36
  • 53
StuStirling
  • 15,601
  • 23
  • 93
  • 150

2 Answers2

2

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.

Zefick
  • 2,014
  • 15
  • 19
  • 1
    Please u must use BigDecimal class in Java! It´s has a method to round up and get the format u want like String, double, etc. And the most important thing, you dont loose precision using this class! – Catluc Feb 23 '17 at 21:37
0

This problem is due to the precision of float datatype in the Floating Point Arithmetic of computer. As @Zefick shows in his answer, the representation of 37.35 like float is actually closer to 37.3 than to 37.4; because it is slightly less than 37.35.

The use of double precision solves the problem, but being this a restriction I suggest using a wrapper:

    return format.format(Double.valueOf(String.valueOf(37.35f)));
lcnicolau
  • 3,252
  • 4
  • 36
  • 53