关于java double类型运算的困惑
高洛峰
高洛峰 2017-04-17 17:41:32
0
2
337

请看下面的代码

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么

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
迷茫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template