请看下面的代码
double a = 0.001;
double b = 13.456;
System.out.println(a);
System.out.println(b);
System.out.println(a+b);
System.out.println(b-a);
运算的结果是
0.001
13.456
13.456999999999999
13.455;
表示对结果不太理解,难道ab相加的结果不应该是13.457么
迷茫2017-04-17 17:43:32
Double will lose precision during operation. It is recommended to use java.math.BigDecimal for operation.
高洛峰2017-04-17 17:43:32
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.