0

The following value gives me wrong precision. It is observed with only specific numbers. It might be a floating representation problem, but wanted to know the specific reason.

String m = "154572.49"; //"154,572.49";
Float f = Float.parseFloat(m);
System.out.println(f);

The output it is printing is 154572.48 instead of 154572.49.

RP-
  • 5,827
  • 2
  • 27
  • 46
  • 3
    The reason is that you can't represent infinite many numbers in a finite amount of memory, like 32bit float. Hence, you'll always get the nearest representable number. – Ingo Feb 07 '13 at 11:26

3 Answers3

3

If you want decimal numbers to come out as exactly as you entered them in Java, use BigDecimal instead of float.

Floating point numbers are inherently inaccurate for decimals because many numbers that terminate in decimal (e.g. 0.1) are recurring numbers in binary and floating point numbers are stored as a binary representation.

Jack Aidley
  • 19,439
  • 7
  • 43
  • 70
  • Thanks for your response, Yes I am pretty much used to `BigDecimal` but was working with a third party library where I encountered with this. – RP- Feb 07 '13 at 11:30
1

You must read this What Every Computer Scientist Should Know About Floating-Point Arithmetic

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

Nishant
  • 54,584
  • 13
  • 112
  • 127
1

Float offers a base 2 representation of a decimal number. When you parse, it is parsing the binary representation of the decimal number that will almost never be exact. You may get .4856 from its binary representation (well, I didn't do the calculation and its just a guess to get you the idea).

KMC
  • 19,548
  • 58
  • 164
  • 253