Float precision with specific numbers

蹲街弑〆低调 提交于 2019-12-02 09:20:17

If you want decimal numbers to come out as exactly as you entered them in Java, use BigDecimal instead of float.

Floating point numbers are inherently inaccurate for decimals because many numbers that terminate in decimal (e.g. 0.1) are recurring numbers in binary and floating point numbers are stored as a binary representation.

You must read this What Every Computer Scientist Should Know About Floating-Point Arithmetic

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

Float offers a base 2 representation of a decimal number. When you parse, it is parsing the binary representation of the decimal number that will almost never be exact. You may get .4856 from its binary representation (well, I didn't do the calculation and its just a guess to get you the idea).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!