教程 decimaljs tutorial

电商金额计算

在电商系统中,金额计算对精度要求极高,使用原生 JavaScript 数值容易出现浮点误差。decimal.js 提供高精度的数值计算支持。

示例场景

计算购物车中多个商品的总价,包含单价、数量及优惠折扣,保证金额精确。

js
import Decimal from 'decimal.js';

// 商品价格和数量
const price1 = new Decimal('99.99');
const quantity1 = new Decimal(2);

const price2 = new Decimal('15.50');
const quantity2 = new Decimal(5);

// 计算总价
const total1 = price1.times(quantity1); // 商品1总价
const total2 = price2.times(quantity2); // 商品2总价

// 计算购物车总价
const cartTotal = total1.plus(total2);

// 应用折扣,例如 10% 折扣
const discountRate = new Decimal('0.9');
const discountedTotal = cartTotal.times(discountRate);

// 保留两位小数,四舍五入
const finalAmount = discountedTotal.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);

console.log(`订单总金额: $${finalAmount.toString()}`);
// 输出: 订单总金额: $232.43

`

关键点说明

  • 使用 .times() 和 .plus() 进行高精度乘法和加法。
  • 折扣计算同样使用 Decimal 保证精度。
  • 最终金额格式化为两位小数,符合金额显示习惯。
  • 避免使用原生 Number 避免累积浮点误差。

通过 decimal.js 实现金额计算,确保电商系统的金额计算准确无误,提升用户信任和系统稳定性。