0

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.

2
  • 3
    Use the BigDecimal class for arbitrary precision signed floats. There are ways to convert a String to it, search other such posts for this. Commented May 26, 2015 at 14:34
  • As per @Kon's suggestion, please use BigDecimal. Not all fractions can be exactly represented in binary, hence the error. Please refer to the linked question for more information. Commented May 26, 2015 at 14:37

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.