主题
货币计算示例
在财务和电商领域,金额计算要求高度精确,避免原生 JavaScript 浮点数误差。decimal.js 提供了可靠的解决方案。
示例场景
计算购物车中多个商品的总价,涉及加法、乘法和舍入。
js
import Decimal from 'decimal.js';
// 商品单价与数量
const price1 = new Decimal('19.99');
const quantity1 = new Decimal(3);
const price2 = new Decimal('5.75');
const quantity2 = new Decimal(10);
// 计算总价(单价 * 数量)
const total1 = price1.times(quantity1);
const total2 = price2.times(quantity2);
// 计算购物车总价
const cartTotal = total1.plus(total2);
// 保留两位小数,常用于金额显示
const finalAmount = cartTotal.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
console.log(`购物车总价: $${finalAmount.toString()}`);
// 输出: 购物车总价: $97.45
重点说明
- 使用
.times()
做乘法,保证单价与数量的准确计算。 - 使用
.plus()
做加法,避免累积误差。 - 使用
.toDecimalPlaces(2, Decimal.ROUND_HALF_UP)
保留两位小数,并采用银行家舍入,符合财务规范。
建议
- 所有金额运算使用 decimal.js 类型,避免使用原生 Number。
- 统一设置全局舍入模式,确保一致性。
- 显示金额时统一格式化,避免用户界面出现多种精度。
通过 decimal.js 实现货币计算,可以避免精度误差,提升财务数据的准确性和用户体验。