如何精确舍入小数点后三位或更多位的数字?

问题描述 投票:0回答:1

我正在开发购物车系统,在计算过程中遇到了舍入某些金额的一些挑战。以下是我的购物车的详细信息。

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}`);

javascript math rounding calculator
1个回答
0
投票

四舍五入的财务数量会带来十分之几美分的误差。只需其中几个就可以复合成便士甚至更多。

大多数金融系统(全部?)所做的就是“仅对输出进行四舍五入”。让所有中间计算充分利用可用的浮点精度,在 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));

© www.soinside.com 2019 - 2024. All rights reserved.