一、Decimal.js 簡介
decimal.js 是一個用于任意精度算術運算的 JavaScript 庫,它可以完美解決浮點數計算中的精度丟失問題。
官方API文檔:Decimal.js
特性:
-
任意精度計算:支持大數、小數的高精度運算。
-
鏈式調用:簡潔的鏈式操作方式。
-
支持所有常見運算:加減乘除、取冪、平方根、取模等。
-
跨平臺:可以在瀏覽器和 Node.js 中使用。
安裝
在項目中使用 decimal.js 需要先安裝庫:
// 終端輸入命令
npm/cnpm/pnpm install decimal.js
二、Decimal.js 的基本用法
- 創建 Decimal 對象
可以通過構造函數創建 Decimal 對象,支持多種格式的輸入。
import Decimal from 'decimal.js'// 創建 Decimal 對象,最好使用字符串,防止原生js數字過大自帶的精度問題,例如12345678987654321const num1 = new Decimal(0.1);// 可以不要new關鍵字,兩種方法等同Decimal(0.1)
const num2 = new Decimal('0.2');
const num3 = new Decimal(0.3);// 得到的結果是一個Decimal對象,需要使用Decimal對象的toString或者toNumber獲取正常數據
console.log(num1.toString()); // 輸出 "0.1"console.log(num2.toString()); // 輸出 "0.2"
- 基本運算
Decimal.js 支持常見的加、減、乘、除等操作。
const num1 = new Decimal(0.1);
const num2 = new Decimal(0.2);console.log(num1.plus(num2).toString()); // 加法:0.3console.log(num1.minus(num2).toString()); // 減法:-0.1console.log(num1.times(num2).toString()); // 乘法:0.02console.log(num1.div(num2).toString()); // 除法:0.5
- 鏈式調用
可以通過鏈式調用簡化復雜的計算邏輯。
const result = new Decimal(0.1).plus(0.2).times(10).div(3);console.log(result.toString()); // 輸出 "1"
- 比較大小
可以通過 Decimal 提供的比較方法來比較兩個數的大小。
const num1 = new Decimal(0.1);
const num2 = new Decimal(0.2);console.log(num1.lessThan(num2)); // trueconsole.log(num1.greaterThan(num2)); //falseconsole.log(num1.equals(0.1)); // true
- 數學運算
Decimal.js 還支持其他常見的數學操作,例如取冪、平方根等。
const num = new Decimal(2);console.log(num.pow(3).toString()); // 8console.log(num.sqrt().toString()); // 1.4142135623730951
- 四舍五入與精度控制
Decimal.js 提供了方便的四舍五入和精度控制方法:
const num = new Decimal(1.23456789);console.log(num.toFixed(2)); // 1.23console.log(num.toPrecision(4)); // 1.235console.log(num.round().toString()); // 1
原文博客: Decimal.js
個人博客: Decimal.js