Decimal.js 中文使用文档

一、安装与导入

安装

bash
pnpm add decimal.js

项目配置

unplugin-auto-import 配置:

javascript
AutoImport({
  imports: [
    {
      "decimal.js": ['Decimal'],
    }
  ],
  dts: "src/auto-import.d.ts",
})

二、基本用法

创建 Decimal 实例

javascript
const num1 = new Decimal(123);           // 从数字
const num2 = new Decimal('456.789');     // 从字符串(推荐)
const num3 = new Decimal(num2);          // 从另一个 Decimal
const num4 = new Decimal('1e10');        // 科学计数法

最佳实践 :传入浮点数时建议使用字符串形式,避免 JavaScript 浮点精度问题。

三、四则运算

加法 .plus()

javascript
const a = new Decimal('0.1');
const b = new Decimal('0.2');
const result = a.plus(b);  // 结果: 0.3
console.log(result.toString()); // "0.3"

减法 .minus()

javascript
const a = new Decimal('10');
const b = new Decimal('3.7');
const result = a.minus(b);  // 结果: 6.3

乘法 .times()

javascript
const a = new Decimal('12.5');
const b = new Decimal('4');
const result = a.times(b);  // 结果: 50

除法 .dividedBy()

javascript
const a = new Decimal('10');
const b = new Decimal('3');
const result = a.dividedBy(b);  // 结果: 3.3333333333333333

四、小数位数处理

保留小数位 .toFixed()

javascript
const num = new Decimal('3.1415926');

num.toFixed(2);   // "3.14" (四舍五入保留2位)
num.toFixed(4);   // "3.1416"
num.toFixed(0);   // "3"

设置精度 .precision()

javascript
const num = new Decimal('1234.5678');
num.precision(6); // "1234.57" (保留6位有效数字)

向上取整 .ceil()

javascript
new Decimal('1.23').ceil().toNumber();  // 2
new Decimal('-1.23').ceil().toNumber(); // -1

向下取整 .floor()

javascript
new Decimal('1.99').floor().toNumber();  // 1
new Decimal('-1.99').floor().toNumber(); // -2

四舍五入 .round()

javascript
new Decimal('1.5').round().toNumber();  // 2
new Decimal('1.4').round().toNumber();  // 1

五、比较运算

等于 .equals()

javascript
new Decimal('0.1').equals('0.1');    // true
new Decimal('0.1').equals(0.1);      // true(注意:JavaScript 0.1 存在精度问题)

大于 .greaterThan()

javascript
const a = new Decimal('10');
const b = new Decimal('5');

a.greaterThan(b);       // true

小于等于 .lessThanOrEqualTo()

javascript
const a = new Decimal('10');
const b = new Decimal('5');

a.lessThanOrEqualTo(b); // false

最大最小值

javascript
// 最大值
Decimal.max(new Decimal('10'), new Decimal('20'), new Decimal('15')); // Decimal(20)

// 最小值
Decimal.min(new Decimal('10'), new Decimal('20'), new Decimal('15')); // Decimal(10)

六、其他常用方法

转换类型

javascript
const num = new Decimal('123.456');

num.toNumber();   // 123.456(转换为原生数字)
num.toString();   // "123.456"
num.toFixed(2);   // "123.46"(字符串形式)
num.toJSON();     // "123.456"(用于 JSON 序列化)

取模 .mod()

javascript
new Decimal('10').mod(new Decimal('3')).toNumber();  // 1

幂运算 .pow()

javascript
new Decimal('2').pow(10).toNumber();  // 1024

开方 .sqrt()

javascript
new Decimal('16').sqrt().toNumber();  // 4

绝对值 .abs()

javascript
new Decimal('-123').abs().toNumber(); // 123

取反 .negated()

javascript
new Decimal('123').negated().toNumber(); // -123