Java floating point numbers

The two floating-point types in Java: float and double

floating-point values ​​are not suitable for calculations where rounding errors cannot be tolerated. The main cause of rounding errors is that floating-point values ​​are represented in the binary system, and the fraction 1/10 cannot be represented exactly in the binary system, just as the fraction 1/3 cannot be represented exactly in decimal.

So if you don't allow any rounding errors in numerical calculations, you should use the BigDecimal class.

How can the fraction 1/10 not be exactly represented in the binary system?
Converting 1/10 into binary is 1/1010, and the result is an infinite loop of decimals, so binary cannot use finite digits to represent 0.1.
Binary can use finite digits to represent some numbers, such as 0.5, 0.25, etc.
0.5, 0.25 are converted into binary as 101/1010, 11001/1100100, so binary can use a limited number of digits to represent 0.5, 0.25, etc.

Fractions 1/3 cannot be represented exactly in decimal.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326728341&siteId=291194637