This is because floating point numbers in computers may (note, it is possible) be inaccurate. It can only be infinitely close to the exact value, but cannot be completely accurate. Why is this so? This is determined by the storage rules of floating point numbers. Let's first look at how to convert the decimal decimal number 0.4 into a binary decimal, using the "multiplied by 2, rounded, and arranged in order" method (don't understand? This is a no-brainer, it's too basic ), we found that 0.4 cannot be accurately represented in binary. In the world of binary numbers, it is an infinitely looping decimal. That is to say, it cannot be "displayed", let alone stored in memory (floating point number The storage includes three parts: sign bit, exponent bit, and mantissa (no details will be introduced). It can be understood that there is no way to accurately represent 1/3 in the decimal world, and of course there is no way to accurately represent 1/5 in the binary world. (If binary also has fractions, it can be expressed). In the binary world, 1/5 is an infinitely recurring decimal.
Double will lose precision during operation. It is recommended to use java.math.BigDecimal for operation.
This is because floating point numbers in computers may (note, it is possible) be inaccurate. It can only be infinitely close to the exact value, but cannot be completely accurate. Why is this so? This is determined by the storage rules of floating point numbers. Let's first look at how to convert the decimal decimal number 0.4 into a binary decimal, using the "multiplied by 2, rounded, and arranged in order" method (don't understand? This is a no-brainer, it's too basic ), we found that 0.4 cannot be accurately represented in binary. In the world of binary numbers, it is an infinitely looping decimal. That is to say, it cannot be "displayed", let alone stored in memory (floating point number The storage includes three parts: sign bit, exponent bit, and mantissa (no details will be introduced). It can be understood that there is no way to accurately represent 1/3 in the decimal world, and of course there is no way to accurately represent 1/5 in the binary world. (If binary also has fractions, it can be expressed). In the binary world, 1/5 is an infinitely recurring decimal.