首页
/ decimal.js 任意精度十进制数处理库使用指南

decimal.js 任意精度十进制数处理库使用指南

2026-02-06 05:44:25作者:袁立春Spencer

decimal.js 是一个用于 JavaScript 的任意精度十进制数类型库,主要解决在 JavaScript 中进行高精度计算时遇到的精度损失问题。特别适用于财务计算、科学计算等对数值精确度要求极高的场景。

功能特性

  • 支持整数和浮点数的高精度运算
  • 简单但功能完整的 API 接口
  • 复现了 JavaScript 的 Number.prototypeMath 对象的大部分方法
  • 支持十六进制、二进制和八进制数值
  • 比 Java 的 BigDecimal 的 JavaScript 版本更快、更小、更易用
  • 无外部依赖
  • 广泛平台兼容性:仅使用 JavaScript 1.5 (ECMAScript 3) 特性
  • 包含 TypeScript 声明文件:decimal.d.ts

安装与引入

通过 npm 安装

npm install decimal.js

浏览器中直接引入

<script src='path/to/decimal.js'></script>

<script type="module">
  import Decimal from './path/to/decimal.mjs';
</script>

Node.js 中使用

const Decimal = require('decimal.js');

import Decimal from 'decimal.js';

import {Decimal} from 'decimal.js';

基本使用方法

创建 Decimal 对象

import { Decimal } from 'decimal.js';

// 通过数字创建
let num1 = new Decimal(123.4567);

// 通过字符串创建(推荐避免精度损失)
let num2 = new Decimal('123456.7e-3');

// 通过已有 Decimal 实例创建
let num3 = new Decimal(num1);

基本算术运算

let a = new Decimal('0.1');
let b = new Decimal('0.2');

let sum = a.plus(b);           // 加法
let difference = a.minus(b);   // 减法  
let product = a.times(b);      // 乘法
let quotient = a.dividedBy(b); // 除法

console.log(sum.toString());        // '0.3'
console.log(difference.toString()); // '-0.1'
console.log(product.toString());    // '0.02'
console.log(quotient.toString());   // '0.5'

避免精度损失的示例

// 使用数字字面量会导致精度损失
new Decimal(1.0000000000000001)         // '1'
new Decimal(0.7 + 0.1)                  // '0.7999999999999999'

// 使用字符串可避免精度问题
new Decimal('1.0000000000000001')       // '1.0000000000000001'
new Decimal('0.8')                      // '0.8'

高级功能

方法链式调用

let x = new Decimal(10);
let y = new Decimal(3);
let z = new Decimal(2);

let result = x.dividedBy(y).plus(z).times(9).floor();
console.log(result.toString()); // '45'

数学函数支持

let value = new Decimal(255.5);

value.toExponential(5);     // '2.55500e+2'
value.toFixed(5);           // '255.50000'  
value.toPrecision(5);       // '255.50'

// 数学运算
Decimal.sqrt('6.98372465832e+9823');  // '8.3568682281821340204e+4911'
Decimal.pow(2, 0.0979843);            // '1.0702770511687781839'

分数表示

let pi = new Decimal(355).dividedBy(113);  // '3.1415929204'
pi.toFraction();                           // [ '7853982301', '2500000000' ]
pi.toFraction(1000);                       // [ '355', '113' ]

实际应用案例

财务计算

// 商品价格计算
const price = new Decimal('12.34');
const quantity = new Decimal('10');
const taxRate = new Decimal('0.08');

const subtotal = price.times(quantity);
const tax = subtotal.times(taxRate);
const total = subtotal.plus(tax);

console.log(`小计: $${subtotal.toFixed(2)}`);
console.log(`税费: $${tax.toFixed(2)}`);  
console.log(`总计: $${total.toFixed(2)}`);

科学计算

// 高精度科学计算
const sampleWeight = new Decimal('0.000123456');
const numberOfSamples = new Decimal('1000');
const concentration = new Decimal('0.000000001');

const totalWeight = sampleWeight.times(numberOfSamples);
const totalSubstance = totalWeight.times(concentration);

console.log(`总重量: ${totalWeight.toPrecision(10)}`);
console.log(`物质总量: ${totalSubstance.toScientific()}`);

配置选项

可以配置全局的精度和舍入模式:

// 设置默认 Decimal 构造函数的精度和舍入模式
Decimal.set({ precision: 5, rounding: 4 });

// 创建独立的 Decimal 构造函数
const CustomDecimal = Decimal.clone({ precision: 9, rounding: 1 });

let x = new Decimal(5);
let y = new CustomDecimal(5);

x.div(3);  // '1.6667'
y.div(3);  // '1.66666666'

测试与验证

项目包含完整的测试套件,可以通过以下命令运行测试:

npm test

或者运行单个测试模块:

node test/modules/toFraction

在浏览器中打开 test/test.html 也可以运行测试。

decimal.js 为 JavaScript 开发者提供了强大的高精度数值计算能力,特别适合需要精确计算的金融、科学和工程应用场景。

登录后查看全文
热门项目推荐
相关项目推荐