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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top