Decimal.js 的常用方法

Decimal.js是一个用于高精度计算的JavaScript库,特别适用于需要避免浮点数精度问题的场景,比如金融计算。

1. 安装与引入

# 通过 npm 安装
npm install decimal.js

// 浏览器环境
<script src="decimal.js"></script>
 
// Node.js 环境
const Decimal = require('decimal.js');


2. 基本用法

创建实例
const a = new Decimal(123.456);      // 从数字创建
const b = new Decimal('123.456');    // 从字符串创建(推荐,避免精度丢失)
const c = new Decimal('1.23e+5');    // 科学计数法

克隆对象

const d = new Decimal(a); // 浅拷贝
const e = a.clone();      // 深拷贝


3. 数学运算

四则运算
const x = new Decimal(10);
const y = new Decimal(3);
 
x.plus(y);    // 加法 → 13
x.minus(y);   // 减法 → 7
x.times(y);   // 乘法 → 30
x.dividedBy(y); // 除法 → 3.333...

幂运算与取模

const a = new Decimal(5);
a.pow(3);     // 5³ → 125
a.mod(3);     // 5 % 3 → 2

链式操作

new Decimal(2)
  .times(3)
  .plus(5)
  .dividedBy(2); // (2*3+5)/2 = 5.5


4. 精度控制

设置全局精度
Decimal.set({ precision: 20, rounding: 4 }); // 默认精度20位,四舍五入模式

单个实例精度

const a = new Decimal(1.2345);
a.toDecimalPlaces(2); // 保留两位小数 → 1.23
a.toSignificantDigits(3); // 保留三位有效数字 → 1.23

舍入模式

const modes = {
  0: Decimal.ROUND_UP,     // 向上取整
  1: Decimal.ROUND_DOWN,   // 向下取整
  2: Decimal.ROUND_CEIL,   // 向正无穷取整
  3: Decimal.ROUND_FLOOR,  // 向负无穷取整
  4: Decimal.ROUND_HALF_UP,// 四舍五入(默认)
  5: Decimal.ROUND_HALF_DOWN,
  6: Decimal.ROUND_HALF_CEIL,
  7: Decimal.ROUND_HALF_FLOOR,
  8: Decimal.ROUND_HALF_EVEN
};
 
new Decimal(2.5).toDecimalPlaces(0, modes[4]); // → 3
 

5. 比较与判断

const a = new Decimal(10);
const b = new Decimal(10.00);
 
a.equals(b);    // 严格相等 → true
a.equalTo(b);   // 允许精度差 → true
a.greaterThan(b); // 大于 → false
a.lessThan(b);  // 小于 → false


6. 格式化输出

const num = new Decimal(1234.5678);
 
num.toFixed();          // "1235"(默认0位小数)
num.toFixed(2);         // "1234.57"
num.toFraction();       // 分数形式 → [12345678, 10000]
num.toExponential(3);   // 科学计数法 → "1.235e+3"
num.toLocaleString();   // 本地化格式 → "1,234.57"


7. 类型转换

const a = new Decimal(123.45);
 
a.toNumber();    // 转换为浮点数 → 123.45
a.toString();    // 转换为字符串 → "123.45"
a.toJSON();      // 序列化为JSON → "123.45"


8. 高级功能

对数运算
const x = new Decimal(10);
x.ln();          // 自然对数 → 2.302585093...
x.log10();       // 常用对数 → 1
x.log(2);        // 以2为底的对数 → 3.321928095...

三角函数

const d = new Decimal(Math.PI / 4);
d.sin();         // sin(π/4) → 0.707106781...
d.cos();         // cos(π/4) → 0.707106781...
d.tan();         // tan(π/4) → 1
统计学函数
const arr = [1, 2, 3, 4, 5];
Decimal.mean(arr);    // 平均值 → 3
Decimal.sum(arr);     // 总和 → 15
Decimal.variance(arr); // 方差 → 2.5

适用场景

  • 金融计算(货币、利率、税费)
  • 科学计算(物理、化学公式)
  • 需要精确小数的任何场景
  • 避免浮点误差的累积
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值