Using doubles in multiplication (java)

This question already has an answer here:

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

  • Since you are dealing with values in a shopping cart and double 's are only precise up to a point, I would recommend that you use BigDecimal 's instead because they provide an exact representation of a number. The imprecision of doubles is what's causing your incorrect console output.

    import java.math.BigDecimal;
    
    BigDecimal dynamicRope = new BigDecimal("4"); // example value of 4
    BigDecimal dynamicRopeCost = new BigDecimal("5.50"); // example value of 5.50
    
    // Initialize the other variables as BigDecimal's here
    
    System.out.println("Your total comes to $" +
                        dynamicRope.multiply(dynamicRopeCost)
                        .add(staticRope.multiply(staticRopeCost))
                        .add(webbing.multiply(webbingCost)));
    
    链接地址: http://www.djcxy.com/p/85820.html

    上一篇: 计算非常确切的数字

    下一篇: 在乘法中使用双精度(java)