我有以下值,用作测试数据来执行减法。
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/