Js实现decimal
在JavaScript中处理Decimal(高精度小数)
JavaScript的Number类型使用双精度浮点数(IEEE 754标准),可能导致精度问题。以下是几种处理Decimal的方案:
使用BigInt处理整数
BigInt适合处理大整数运算,但不支持小数:
const bigIntValue = BigInt("12345678901234567890");
console.log(bigIntValue + 1n); // 12345678901234567891n
使用decimal.js库
decimal.js是专门处理高精度小数的流行库:

// 安装:npm install decimal.js
const Decimal = require('decimal.js');
// 精确计算
const sum = new Decimal(0.1).plus(new Decimal(0.2));
console.log(sum.toString()); // "0.3"
// 保留两位小数
const result = new Decimal(1).dividedBy(3).toFixed(2);
console.log(result); // "0.33"
使用bignumber.js库
bignumber.js提供任意精度的小数运算:
const BigNumber = require('bignumber.js');
const x = new BigNumber(0.1);
const y = x.plus(0.2);
console.log(y.toString()); // "0.3"
浏览器内置方案
现代浏览器支持Intl.NumberFormat进行格式化:

const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
console.log(formatter.format(1.005)); // "1.01"
自定义解决方案
对于简单场景,可以放大为整数计算:
function decimalAdd(a, b) {
const multiplier = Math.pow(10, Math.max(
a.toString().split('.')[1]?.length || 0,
b.toString().split('.')[1]?.length || 0
));
return (a * multiplier + b * multiplier) / multiplier;
}
console.log(decimalAdd(0.1, 0.2)); // 0.3
选择方案时应考虑:
- decimal.js/bignumber.js适合复杂金融计算
- BigInt适合大整数场景
- 简单场景可用放大整数法
- 格式化输出使用Intl.NumberFormat





