> 技术文档 > 前端精度计算:Decimal.js 基本用法与详解

前端精度计算:Decimal.js 基本用法与详解


一、Decimal.js 简介

decimal.js 是一个用于任意精度算术运算的 JavaScript 库,它可以完美解决浮点数计算中的精度丢失问题。

官方API文档:Decimal.js

特性:

  1. 任意精度计算:支持大数、小数的高精度运算。

  2. 链式调用:简洁的链式操作方式。

  3. 支持所有常见运算:加减乘除、取幂、平方根、取模等。

  4. 跨平台:可以在浏览器和 Node.js 中使用。

安装
在项目中使用 decimal.js 需要先安装库:

// 终端输入命令 npm/cnpm/pnpm install decimal.js

二、Decimal.js 的基本用法

  1. 创建 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\"
  1. 基本运算
    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
  1. 链式调用
    可以通过链式调用简化复杂的计算逻辑。
const result = new Decimal(0.1).plus(0.2) .times(10) .div(3);console.log(result.toString()); // 输出 \"1\"
  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
  1. 数学运算
    Decimal.js 还支持其他常见的数学操作,例如取幂、平方根等。
const num = new Decimal(2);console.log(num.pow(3).toString()); // 8console.log(num.sqrt().toString()); // 1.4142135623730951
  1. 四舍五入与精度控制
    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