我具有以下值,用作执行减法的测试数据。
订单总额= $ 17.99
项目小计= $ 17.99
折扣= 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
),以便获得正确的结果。
答案 0 :(得分:0)
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);