说一说 JS 精度丢失和解决方案
JS 精度丢失源于 IEEE 754 存储限制,主要体现在小数运算和超大整数场景,可使用 decimal.js/big.js 等专业库处理
JS 精度丢失和丢失场景
shell
# 为何精度丢失?
JavaScript 采用 IEEE 754 双精度浮点数 标准存储数值,这是精度丢失的核心原因
# 精度丢失的场景
1. 小数运算
console.log(0.1 + 0.2); # 0.30000000000000004(而非 0.3)
2. 大整数:当整数超过 2^53(约 9007199254740992,16位数)时,无法被精确表示(如 9007199254740993 会被存储为 9007199254740992)
console.log(9007199254740993); # 9007199254740992(溢出)
3. 数值转字符串/解析
console.log(1234567890123456789); # 1234567890123456800(舍入)精度丢失解决方案
shell
# 处理小数运算
简单小数运算可使用 decimal.js/big.js 等专业库处理
# 处理大整数运算
大整数优先用 ES6 BigInt 或字符串 + decimal.js高精度库处理,避免溢出代码示例
js
// 示例
const Decimal = require('decimal.js');
// 小数运算
const a = new Decimal(0.1);
const b = new Decimal(0.2);
console.log(a.plus(b).toString()); // 0.3
// 大整数运算
const c = new Decimal('9007199254740993');
const d = new Decimal('1');
console.log(c.plus(d).toString()); // 9007199254740994
// 乘法/除法
console.log(new Decimal(1.23).times(4.56).toString()); // 5.6088