我正在开发购物车系统,在计算过程中遇到了舍入某些金额的一些挑战。以下是我的购物车的详细信息。
itemPrice = 0.99;
itemQuantity = 10;
totalPrice = 9.90; /* 0.99 * 10 */
这里我对
totalPrice
金额应用25%的折扣券
discountedPrice = 2.475 /* (9.90 * 25) / 100 */
totalPriceAfterDiscount = 7.425 /* 9.90 - 2.475 */
请提供有关如何将
discountedPrice
和 totalPriceAfterDiscount
金额四舍五入到小数点后两位的说明,确保它们的总和等于 totalPrice
。
将两个数字四舍五入后,值如下:
discountedPrice
= 2.48
和 totalPriceAfterDiscount
= 7.43
。 2.48
和 7.43
之和等于 9.91
。
const afterDiscount = Math.round((7.425 + Number.EPSILON) * 100) / 100;
const discountedAmount = Math.round((2.475 + Number.EPSILON) * 100) / 100;
const total = afterDiscount + discountedAmount;
console.log(`afterDiscount: ${afterDiscount}`);
console.log(`discountedAmount: ${discountedAmount}`);
console.log(`total: ${total}`);
四舍五入的财务数量会带来十分之几美分的误差。只需其中几个就可以复合成便士甚至更多。
大多数金融系统(全部?)所做的就是“仅对输出进行四舍五入”。让所有中间计算充分利用可用的浮点精度,在 JS 中大约为小数点后 15 位。 OP代码过早地舍入了几个中间计算。相比之下,这段代码清楚地描绘了输入和输出,并且只对输出进行四舍五入......
// inputs
const itemPrice = 0.99;
const itemQuantity = 10;
const discount = 0.25;
// notice no rounding, and no hard-coded intermediate values
let totalPrice = itemQuantity * itemPrice;
let discountAmount = totalPrice * discount;
let priceAfterDiscount = totalPrice - discountAmount;
// compare unrounded values
console.log("Unrounded totalPrice", totalPrice);
console.log("Unrounded theoretical total", discountAmount + priceAfterDiscount);
console.log("totalPrice appropriate for output", "$" + totalPrice.toFixed(2));