search

Home  >  Q&A  >  body text

Java中double相减为什么会出现不精确的现象?

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

高洛峰高洛峰2811 days ago839

reply all(5)I'll reply

  • 阿神

    阿神2017-04-17 17:48:37

    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...🎜

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:48:37

    Use BigDecimal in Java for precise calculation of floating point numbers

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 17:48:37

    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.

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:48:37

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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:48:37

    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?

    reply
    0
  • Cancelreply