-2

I don't know whether this question is asked before. I couldn't find it in searches.

System.out.println(1.00 - 9*.10);

the above statement prints out 0.09999999999999998 instead of simply 0.01

I know this is a well known problem in JAVA but i want to know the reason why it is so. Can someone guide me to the implementation details of float and explain the reason.

4
  • Floating point arithmetic. Commented Dec 20, 2013 at 12:34
  • 4
    This question have been answered 99.09999999999999998 times on SO Commented Dec 20, 2013 at 12:35
  • because 0f String-float-string round robin. Commented Dec 20, 2013 at 12:43
  • @ManuViswam It's because 9*0.1 = 0.9 in decimal, but in base two it's approximately equal to 0.900000000000001387778780781446, because there's no base two representation of 0.9. But as mentioned by others this question has a lot of answers here already... Commented Dec 20, 2013 at 12:47

1 Answer 1

1

It's not a problem with java, it's a fundamental problem of the way floating point and double precision numbers are stored and processed in pretty much every language and on every processor.

Because of the way it stores the number it cannot (except in very rare cases) store the number precisely.

A full description of why can be found here: http://en.wikipedia.org/wiki/Single-precision_floating-point_format

You can use things such as BigDecimal to store any precision of number without this issue, however it will run much slower so you have a trade-off of precision vs performance.

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

1 Comment

Yep - do that instead ;) System.out.println(BigDecimal.ONE.subtract(BigDecimal.valueOf(9).multiply(new BigDecimal(".1"))).toString());

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.