Corbella
Corbella

Reputation: 1812

String to Float is not working in java?

The problem is simple:

float f1 = Float.parseFloat("41.975779") 
//Value for f1 is 41.97578  -> An error of 1ppm

And even worse!!

float f2 = Float.parseFloat("41.975645") 
//Value for f2 is 41.975643  -> An error of 2ppm

It doesn't matter if I use Float.parseFloat or Float.valueOf, they both give the same result.

Note: This problem occurs me when programing in android, I didn't try it in pure-java but I assume will be the same result.

Upvotes: 0

Views: 758

Answers (1)

paxdiablo
paxdiablo

Reputation: 882596

Your string to float conversions are working exactly as advertised, although obviously not exactly as you expect :-)

IEEE754 single precision floating point values (as used in float) only have a precision of about seven decimal digits.

If you want more precision, use double, which provides about fifteen decimal digits, or switch to BigDecimal for arbitrary precision.

Just be aware that no encoding scheme can give you infinite precision, there will always be some values that can't be represented (unless you switch to symbolic representation of course).

Upvotes: 3

Related Questions