6

I have just a basic question that why there are discrepancies between the below statements?

System.out.printf("%.2f \n", 55050000.41f);
System.out.printf("%.2f \n", 50.41f);

Output

55050000.00 
50.41 

The first statement removed a decimal value and why not for 2nd statement?

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Vinit Solanki
  • 1,863
  • 2
  • 15
  • 29
  • 2
    The computer is a finite machine, while float are not – Manuel Selva Mar 12 '21 at 09:43
  • In other words: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – GhostCat Mar 12 '21 at 09:45
  • duplicate: [Decimal precision of floats](https://stackoverflow.com/q/3310276/995714), [Java float 123.129456 to 123.12 without rounding](https://stackoverflow.com/q/5051395/995714) – phuclv Mar 12 '21 at 09:50
  • 1
    @GhostCat I don't think this is about floats not storing decimal numbers exactly. It just seems to be a precision issue. – matt Mar 12 '21 at 09:50
  • 1
    Does this answer your question? [Displayed precision of Java floating-point](https://stackoverflow.com/questions/54869876/displayed-precision-of-java-floating-point) – phuclv Mar 12 '21 at 09:50
  • seems there are many healthy conversations on https://stackoverflow.com/questions/588004/is-floating-point-math-broken, so can't say it really that my answer, can say once go through it. – Vinit Solanki Mar 12 '21 at 09:57
  • @matt The *reason* why floats aren't storing (some) decimal numbers exactly is the same that "precision" is about, in the end. – GhostCat Mar 12 '21 at 09:57
  • @GhostCat I think there is a difference. Being unable to store 0.1 because it is a repeating number versus being unable to store "12345678.5" because there are too many decimal digits. Fundamentally they're both a limitation in precision though. – matt Mar 12 '21 at 10:10

1 Answers1

8

By default floating point numbers in Java are converted to 64bit double, but since you're using the f suffix the number will be interpreted as a 32bit float.

The number is so big that it doesn't fit 32bit without losing precision and 55050000 is the closest possible number.

You can play around with floats here. If you change the last bit you can see the number increases by 4.

You probably don't want to use the f suffix unless you're working with limited space.

DerMaddi
  • 649
  • 2
  • 12
  • If remove the f suffix from the values then doesn't losing the decimal values. – Vinit Solanki Mar 12 '21 at 10:07
  • 1
    Without the f suffix you get higher precision, because double has much longer mantissa 52bit vs. 23bit. In this case the mantissa would look like `5.50500004099999964237213134766E7` -> `55050000.4099999964237213134766` -> `55050000.41` – DerMaddi Mar 12 '21 at 10:25