Java中double相减为什么会出现不精确的现象?
高洛峰
高洛峰 2017-04-17 17:46:37
0
5
824

double s = 5.3;
double s1 = 4.2;
System.out.println(s-s1);
输出1.0999999999999996

高洛峰
高洛峰

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

reply all(5)
阿神

The essence of the float and double types in Java's basic data types are floating point numbers. Floating point numbers cannot store precise data. In this case, when floating point numbers are calculated, the calculation result will not be an accurate value;

Therefore, Java provides a class BigDecimal. If you need to perform precise data operations (such as amount), you can use this class. This is called curve to save the country...BigDecimal,如果需要进行精确的数据运算(比如金额),就可以使用该类,这叫曲线救国...

关于浮点数的底层实现及其原理,这个在计算机原理

Regarding the underlying implementation and principles of floating point numbers, this is often discussed in courses such as Computer Principles. You can find relevant information by yourself...🎜
迷茫

Use BigDecimal in Java for precise calculation of floating point numbers

巴扎黑

Thanks for the invitation! I can't explain why the precision is lost, but I know how to solve it. It is recommended to convert double and other types to String before calculation, and then put it into java.math.BigDecimal for calculation. Use java when calculating. math.BigDecimal comes with its own operation methods, such as add() and pide(). . Wait, a BigDecimal object will be returned after calculation, and then converted to basic data types using doubleValue(), intValue() and other methods.

迷茫

Thank you for the invitation. You can refer to this article for this question https://zm8.sm-tc.cn/?src=http%3A%2F%2Fz...

伊谢尔伦

Because computer arithmetic is binary.

The conversion of 0.1 in decimal into binary is an infinitely recurring decimal and must be truncated.

For addition and subtraction of decimal currencies, you can use the BigDecimal type (called Decimal in some languages) to avoid truncation errors.

You can also define a number class yourself, like matlab does.

Error and error are two different things. The difference at the end doesn’t matter in most cases.

For example: Use double-precision floating point numbers to calculate the circumference of the earth. The truncation error is on the order of 0.000001 millimeters. Does it matter?

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