java - 对 double 值进行减法时未得到预期结果

标签 java double bigdecimal

我有以下值,用作测试数据来执行减法。

order total = $17.99

item Sub Total = $17.99

discount = 20

String orderTotal = "17.99"
String itemSubTotal = "17.99"
String discountPercent = "20"

double discountPercent = Double.parseDouble(discount);

// calculate the discount if given in percentage
double discountAmount = (Double.parseDouble(itemSubTotal) * discountPercent) / 100;
    
// round of the amount
double discountAmount = round(discountAmount, 2);

Double finalOrderTotal = (Double.parseDouble(orderTotal)) - discountAmount;

System.out.println("---------------------"+finalOrderTotal);

这是对值进行四舍五入的方法:

public static double round(double value, int numberOfDigitsAfterDecimalPoint) 
{
    BigDecimal bigDecimal = new BigDecimal(value);
    bigDecimal = bigDecimal.setScale(numberOfDigitsAfterDecimalPoint,
            BigDecimal.ROUND_HALF_UP);
    return bigDecimal.doubleValue();
}

因此手动计算预期结果将是 17.99 - 3.60 = 14.39 但我得到的是 14.389999999999999

我已经尝试过BigDecimal正如同一类型问题中所建议的。但为此我必须再做一轮finalOrderTotal 。不是吗?

有人可以帮助我在我进行计算时获得简单的代码(使用 BigDecimal ),以便我可以获得正确的结果。

最佳答案

    String orderTotal = cart.getOrdertotal();
    String itemSubTotal = cart.getItemPrice();

    String orderTotal1 = orderTotal.replace(currency, "");
    String itemSubTotal1 = itemSubTotal.replace(currency, "");

    double discountPercent = Double.parseDouble(discount);

    // calculate the discount if given in percentage
    double discountAmount =
            (Double.parseDouble(itemSubTotal1) * discountPercent) / 100.0;

    // round of the amount
    double discountAmount = round(discountAmount, 2);

    Double finalOrderTotal = (Double.parseDouble(subTotal1)) - discountAmount;
    System.out.println("---------------------"+finalOrderTotal);

关于java - 对 double 值进行减法时未得到预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51558975/

相关文章:

java - fragment 中微调器的 setOnItemSelectedListener()

swift - 你怎么能在swift中将一个数字 append 到一个double

java - ClassCastException : java. lang.Double 与 java.math.BigDecimal 不兼容

c - 将 double 转换为 int 会返回向下舍入的数字吗?

html - <input> 框中的文本下划线

java - 从 BigDecimal [ ] 添加值

Java DecimalFormat HALF_UP 舍入错误

java - 中断 hibernate 线程

Java Web 启动 : How to make the system download the file every time the file changes

java - 不是 JAX-WS 中的有效服务异常