Big.js 教程
最后修改于 2023 年 10 月 18 日
在本文中,我们将展示如何使用 Big.js 模块在 JavaScript 中进行任意精度的大十进制算术运算。
Big.js
Big.js 是一个用于任意精度十进制算术运算的小巧、快速的 JavaScript 库。
在本文中,我们将在 Node 应用程序中使用 Big.js。
设置 Big.js
首先,我们安装 Big.js。
$ node -v v18.2.0
我们使用 Node 版本 18.2.0。
$ npm init -y
我们启动一个新的 Node 应用程序。
$ npm i big.js
我们使用 npm i big.js
命令安装 Big.js。
JavaScript 数字精度错误
在第一个例子中,我们展示了 JavaScript 数字在进行任意精度算术运算时不够精确。
count_currency.js
var sum = 0; // two euros fifty-five cents var amount = 2.55; for (let i = 0; i < 100000; i++) { sum += amount; } console.log(sum);
在这个例子中,我们将两个欧元五十五分重复加 10 万次。
$ nodejs numbers.js 254999.9999995398
计算结果有错误。
Big.js 示例
在下一个例子中,我们使用 Big.js 来纠正这个错误。
main.js
import Big from 'big.js'; let val = new Big(0.0); let amount = new Big(2.55); let sum = val.plus(amount).times(100000); console.log(sum.toFixed(2));
使用 Big.js 库,计算是精确的。
import Big from 'big.js';
我们从 big.js
模块导入 Big
。
let val = new Big(0.0); let amount = new Big(2.55);
我们创建两个大十进制值。
let sum = val.plus(amount).times(100000);
我们将值加 100000 次。请注意,大十进制值是不可变的,因此我们生成一个新的变量。
$ node main.js 255000.00
Big.js pow
pow
提供高精度幂运算。
main.js
import Big from 'big.js'; let val = new Big(0.9); let res = val.pow(3); console.log(res); console.log(0.9 ** 3);
该示例使用 Big.js 和原生 JS 将 0.9 提升到 3 次方。
$ node main.js 0.729 0.7290000000000001
来源
在本文中,我们使用了 Big.js
库在 JavaScript 中进行任意精度算术运算。