安装
npm i mathjs
使用
import { all, create } from "mathjs"; const config = { number: "BigNumber", precision: 20, }; const math = create(all, config); function calc(expression) { if (expression) { return math.number(math.evaluate(expression)); } else { return 0; } } // 可以使用表达式进行计算 console.log(calc(`0.1 + 0.2`)); // 0.3
这里推介使用表达式的方式进行计算,灵活且精确