Addition in Java

This question already has an answer here:

  • Why not use Double or Float to represent currency? 14 answers

  • You can do exact floating point arithmetic in Java using BigDecimal .

    Here is an example:

    BigDecimal a = new BigDecimal("0.0040");
    BigDecimal b = new BigDecimal("0.0005");
    BigDecimal sum = a.add(b);
    

    Also note that BigDecimal and BigInteger (the same for integers) are immutable.


    It's because of floating point numbers, they lose precision and cause the problem you are seeing. Rather use BigDecimal for precision

    链接地址: http://www.djcxy.com/p/85808.html

    上一篇: Python中的相等十进制数

    下一篇: Java中的添加