主题
decimal.js 与原生 Number 的对比
JavaScript 原生的 Number 类型基于 IEEE 754 双精度浮点数实现,存在精度误差,尤其是在小数计算时。decimal.js 则使用任意精度的十进制计算,避免了这些问题。
原生 Number 的精度问题示例
js
console.log(0.1 + 0.2); // 输出: 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // 输出: false
console.log(0.3 - 0.2); // 输出: 0.09999999999999998
console.log(0.3 - 0.2 === 0.1); // 输出: false
使用 decimal.js 进行同样计算
js
import Decimal from 'decimal.js';
const a = new Decimal(0.1);
const b = new Decimal(0.2);
console.log(a.plus(b).toString()); // 输出: "0.3"
console.log(a.plus(b).equals(new Decimal(0.3))); // 输出: true
const c = new Decimal(0.3);
const d = new Decimal(0.2);
console.log(c.minus(d).toString()); // 输出: "0.1"
console.log(c.minus(d).equals(new Decimal(0.1))); // 输出: true
差异总结
特性 | 原生 Number | decimal.js |
---|---|---|
数值表示 | IEEE 754 二进制浮点数 | 任意精度十进制数 |
计算精度 | 浮点误差存在 | 高精度无误差 |
运算结果 | 可能有舍入误差 | 精确可靠 |
API | 基础算术操作 | 丰富的数学运算和格式化 |
适用场景 | 普通计算 | 金融、电商、科学计算等高精度场景 |
decimal.js 通过精确的十进制计算,有效解决了原生 Number 的精度缺陷,是严谨数值计算的理想选择。