处理代码中的运算,避免出现进度丢失
0.1 + 0.2 = 0.30000000000000004
0.3 - 0.1 = 0.19999999999999998
- 安装
pnpm i babel-plugin-decimal.js
- 在项目中的 .babelrc 或者 babel.config.js 中加入 babel-plugin-decimal.js
{
"presets": ["@babel/preset-env"],
"plugins": ["babel-plugin-decimal.js"]
}
// 源码
const add = (a, b) => {
return a + b
}
// 编译后
var Decimal = require('decimal.js');
var add = function add(a, b) {
return new Decimal(a).add(b).toNumber();
};