教程 decimaljs tutorial

基本使用示例

decimal.js 通过 Decimal 类提供高精度数值运算,使用简单且直观。

创建 Decimal 实例

你可以通过多种方式创建 Decimal 对象:

js
import Decimal from 'decimal.js';

const a = new Decimal(0.1);
const b = new Decimal('0.2');
const c = new Decimal(a);

`

基本算术运算

decimal.js 支持常见的加、减、乘、除运算:

js
const a = new Decimal(0.1);
const b = new Decimal(0.2);

console.log(a.plus(b).toString());    // "0.3"
console.log(b.minus(a).toString());   // "0.1"
console.log(a.times(b).toString());   // "0.02"
console.log(b.div(a).toString());     // "2"

注意,所有运算方法均返回新的 Decimal 实例,保持原始对象不变。

链式调用

decimal.js 支持链式调用,方便连续计算:

js
const result = new Decimal(0.1)
  .plus(0.2)
  .times(3)
  .div(0.3);

console.log(result.toString());  // "3"

通过这些简单示例,你可以快速上手 decimal.js,实现精准数值计算。