Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to parseFloat in Java

I notice some issues with the Java float precision

       Float.parseFloat("0.0065") - 0.001  // 0.0055000000134110451
       new Float("0.027") - 0.001          // 0.02600000000700354575
       Float.valueOf("0.074") - 0.001      // 0.07399999999999999999

I not only have a problem with Float but also with Double.

Can someone explain what is happening behind the scenes, and how can we get an accurate number? What would be the right way to handle this when dealing with these issues?

like image 711
peter Avatar asked Oct 05 '12 18:10

peter


People also ask

How does JavaScript parseFloat work?

The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number.

Which method is used to convert value to float?

The simplest way to do so is using parseFloat() method of Float class in java.


3 Answers

The problem is simply that float has finite precision; it cannot represent 0.0065 exactly. (The same is true of double, of course: it has greater precision, but still finite.)

A further problem, which makes the above problem more obvious, is that 0.001 is a double rather than a float, so your float is getting promoted to a double to perform the subtraction, and of course at that point the system has no way to recover the missing precision that a double could have represented to begin with. To address that, you would write:

float f = Float.parseFloat("0.0065") - 0.001f;

using 0.001f instead of 0.001.

like image 53
ruakh Avatar answered Oct 11 '22 12:10

ruakh


See What Every Computer Scientist Should Know About Floating-Point Arithmetic. Your results look correct to me.

If you don't like how floating-point numbers work, try something like BigDecimal instead.

like image 6
willglynn Avatar answered Oct 11 '22 13:10

willglynn


You're getting the right results. There is no such float as 0.027 exactly, nor is there such a double. You will always get these errors if you use float or double.

float and double are stored as binary fractions: something like 1/2 + 1/4 + 1/16... You can't get all decimal values to be stored exactly as finite-precision binary fractions. It's just not mathematically possible.

The only alternative is to use BigDecimal, which you can use to get exact decimal values.

like image 5
Louis Wasserman Avatar answered Oct 11 '22 13:10

Louis Wasserman