decimal.js的介绍与使用

第三方工具库

# 简介

我们都知道js处理数字的加减乘除的时候,存在精度不够的问题。这个库就是用于解决js计算精度丢失的问题。特别在金融行业对数字精度要求比较高的情况下,这个库就非常有用了。

github链接: https://github.com/MikeMcl/decimal.js (opens new window)

api文档: http://mikemcl.github.io/decimal.js/ (opens new window)

# 基本使用

创建实例:两种方式

let x = new Decimal(10)
let y = Decimal(20)

下面介绍几个常用的方法

# 加法

.add(x, y) ⇒ Decimal

a = Decimal.add(0.1, 0.2)
b = new Decimal(0.1).add(0.2)
a.equals(b) // true

加法的另一种写法

.plus(x) ⇒ Decimal 
c = new Decimal(0.1).plus(0.2) 
c.equals(b) // true

plusadd 的区别先看下截取的部分源码

// Decimal.prototype object
P = { toStringTag: tag }
P.plus = P.add = function (y) {
   // ...省略
}
Decimal.prototype = P

function add(x, y) {
  return new this(x).plus(y)
}
Decimal.add = add

总结:

  1. add函数在构造函数和实例对象都有该方法,plus函数仅在实例上存在;
  2. 实例上addplus实为同一函数,构造函数上的add的方法是进一步封装,实际上也是调用的实例上的plus方法;
  3. 使用上的区别在于,实例调用传一个参数,构造函数调用传两个参数。

# 减法

.sub(x, y) ⇒ Decimal

a = Decimal.sub(0.1, 0.2)
b = new Decimal(0.1).sub(0.2)
a.equals(b)                    // true

.minus(x) ⇒ Decimal 同上plus

# 乘法

.mul(x, y) ⇒ Decimal

a = Decimal.mul(0.1, 0.2)
b = new Decimal(0.1).mul(0.2)
a.equals(b)                    // true

.times(x) ⇒ Decimal 也是一样

# 除法

.div(x, y) ⇒ Decimal

a = Decimal.div(0.1, 0.2)
b = new Decimal(0.1).div(0.2)
a.equals(b)                    // true

.dividedBy(x, y) ⇒ Decimal 同上

像这种有两个能实现一样效果的函数,其实只需要记住其中一种,另一种了解即可,看到别人不同的写法也能理解就好

# 幂次方

.pow(base, exponent) ⇒ Decimal

a = Decimal.pow(0.1, 0.2)
b = new Decimal(0.1).pow(0.2)
a.equals(b)  // true

# 转化

由于计算结果返回的是一个Decimal对象,我们可以转换成 Number 或则 String

let res = Decimal(a).div(Decimal(b)).toNumber()  // 结果转换成 Number
let res = Decimal(a).div(Decimal(b)).toString()  // 结果转换成 String

# 保留有效位数、小数

toSignificantDigits([sd [, rm]]) ⇒ Decimal

// 保留 多少位有效位数(小数位 不会补0,是计算的有效位数)
x = new Decimal(9876.5)
x.toSignificantDigits(4)                 // '9877' 
x.toSignificantDigits(6)                 // '9876.5' 不会补0 只是针对有效位数

.toFixed([dp [, rm]]) ⇒ string

// 保留几位小数 ,跟 js 方法类似
x = new Decimal(3.456)
x.toFixed()  // '3' 
x.toFixed(2)  // '3.46' 
x.toFixed(5)  // '3.45600'

可传的第二个参数为舍入模式:向上取整、向下取整,四舍五入...,默认为四舍五入

// 向下取整
x.toFixed(2, Decimal.ROUND_DOWN)  // '3.45' 
// 向上取整 Decimal.ROUND_UP 
// 四舍五入 Decimal.ROUND_HALF_UP

Decimal.ROUND_UP、Decimal.ROUND_DOWN、Decimal.ROUND_HALF_UP...为常量,对应的值为 0、1、4...

Wonderwall
Oasis