decimal.js 中文版 翻译作者 lixingwu@aliyun.com

decimal.js

一个的任意精度十进制类型JavaScript库. (翻译 lixingwu@aliyun.com)

GitHub | Gitee

API

在 Gitee 的 README 上有快速入门的介绍。

在下面的所有示例中, var 和分号不显示, 如果注释后面的内容带有引号表示已经调用了 toString 方法。


在加载库时,会自动根据Decimal的构造函数定义一个Decimal函数。

如果有需要,你可以创建多个Decimal构造函数,每个构造函数都独享自己的配置,例如精度、范围,这些配置只对当前构造函数创建的实例有效。

可以通过调用已经存在Decimal构造函数的 clone 来产生一个新的Decimal构造函数。

构造函数

DecimalDecimal(value) ⇒ Decimal
value: number|string|Decimal
一个合法的 value 可以是 integer 或者 float 类型的数字或者字符串, 包括 ±0±InfinityNaN.
value 没有位数限制,JavaScript 数组的最大值和实际需要的处理时间除外。
value 的允许范围参见最大指数 maxE,最小指数 minE.
和十进制的数字一样,如果数据包含合法的前缀也可初始化, 比如: 十六进制前缀为 0x0X, 二进制前缀为 0b 或者 0B, 八进制前缀为 0o 或者0O
十进制和其它进制的数据都可以使用指数法(浮点数)和普通形式表示。
使用指数法表示时 e 或者 E 表示十进制的十进制幂,p 或者 P 表示非十进制的二次幂。

Returns: 一个新的Decimal对象的实例。

Throws: 无效的 value.

x = new Decimal(9)                       // '9'
y = new Decimal(x)                       // '9'

new Decimal('5032485723458348569331745.33434346346912144534543')
new Decimal('4.321e+4')                  // '43210'
new Decimal('-735.0918e-430')            // '-7.350918e-428'
new Decimal('5.6700000')                 // '5.67'
new Decimal(Infinity)                    // 'Infinity'
new Decimal(NaN)                         // 'NaN'
new Decimal('.5')                        // '0.5'
new Decimal('-0b10110100.1')             // '-180.5'
new Decimal('0xff.8')                    // '255.5'

new Decimal(0.046875)                    // '0.046875'
new Decimal('0.046875000000')            // '0.046875'

new Decimal(4.6875e-2)                   // '0.046875'
new Decimal('468.75e-4')                 // '0.046875'

new Decimal('0b0.000011')                // '0.046875'
new Decimal('0o0.03')                    // '0.046875'
new Decimal('0x0.0c')                    // '0.046875'

new Decimal('0b1.1p-5')                  // '0.046875'
new Decimal('0o1.4p-5')                  // '0.046875'
new Decimal('0x1.8p-5')                  // '0.046875'

Methods 方法

Decimal 构造函数的方法。

abs(绝对值).abs(x) ⇒ Decimal

x: number|string|Decimal

详情查看absoluteValue.

a = Decimal.abs(x)
b = new Decimal(x).abs()
a.equals(b)                    // true
acos(反余弦值).acos(x) ⇒ Decimal

x: number|string|Decimal

详情查看inverseCosine.

a = Decimal.acos(x)
b = new Decimal(x).acos()
a.equals(b)                    // true
acosh(反双曲余弦值).acosh(x) ⇒ Decimal

x: number|string|Decimal

详情查看inverseHyperbolicCosine.

a = Decimal.acosh(x)
b = new Decimal(x).acosh()
a.equals(b)                    // true
add(加法).add(x, y) ⇒ Decimal

x: number|string|Decimal
y: number|string|Decimal

plus 别名.

a = Decimal.add(x, y)
b = new Decimal(x).plus(y)
a.equals(b)                    // true
asin(反正弦值).asin(x) ⇒ Decimal

x: number|string|Decimal

详情查看inverseSine.

a = Decimal.asin(x)
b = new Decimal(x).asin()
a.equals(b)                    // true
asinh(反双曲正弦值).asinh(x) ⇒ Decimal

x: number|string|Decimal

详情查看inverseHyperbolicSine.

a = Decimal.asinh(x)
b = new Decimal(x).asinh()
a.equals(b)                    // true
atan(反正切值).atan(x) ⇒ Decimal

x: number|string|Decimal

详情查看inverseTangent.

a = Decimal.atan(x)
b = new Decimal(x).atan()
a.equals(b)                    // true
atanh(反双曲正切值).atanh(x) ⇒ Decimal

x: number|string|Decimal

详情查看 inverseHyperbolicTangent.

a = Decimal.atanh(x)
b = new Decimal(x).atanh()
a.equals(b)                    // true
atan2(反正切值增强).atan2(y, x) ⇒ Decimal

y: number|string|Decimal
x: number|string|Decimal

计算 yx 的反正切值, 并使用 rounding(舍入) 模式, precision(精确) 到有效数字, 然后返回一个新的 Decimal对象。

yx 的符号用于确定结果所在的象限。

取值范围: [-Infinity, Infinity]
值范围: [-pi, pi]

值范围查看 Pi ,取值范围查看 Math.atan2().

r = Decimal.atan2(y, x)
cbrt(立方根).cbrt(x) ⇒ Decimal

x: number|string|Decimal

详情查看 cubeRoot.

a = Decimal.cbrt(x)
b = new Decimal(x).cbrt()
a.equals(b)                    // true
ceil(上入整数).ceil(x) ⇒ Decimal

x: number|string|Decimal

详情查看 ceil.

a = Decimal.ceil(x)
b = new Decimal(x).ceil()
a.equals(b)                    // true
clone(拷贝) .clone([object]) ⇒ Decimal 构造函数

object: object

返回一个新的Decimal构造函数,该构造函数具有描述对象的设置(请参阅set), 如果省略了object,则和原来的Decimal构造函数具有相同的设置。

Decimal.set({ precision: 5 })
Decimal9 = Decimal.clone({ precision: 9 })

a = new Decimal(1)
b = new Decimal9(1)

a.div(3)                           // 0.33333
b.div(3)                           // 0.333333333

// 相当于 Decimal9 = Decimal.clone({ precision: 9 }):
Decimal9 = Decimal.clone()
Decimal9.set({ precision: 9 })

如果 object'defaults' 属性为 true,那么新的构造函数将使用默认的配置。

D1 = Decimal.clone({ defaults: true })

// 使用默认值(精度precision属性除外)
D2 = Decimal.clone({ defaults: true, precision: 50 })

使用多个 Decimal 构造函数,并不会影响内存使用效率,因为它们之间的功能是共享的。

cos(余弦值).cos(x) ⇒ Decimal

x: number|string|Decimal

详情查看 cosine.

a = Decimal.cos(x)
b = new Decimal(x).cos()
a.equals(b)                    // true
cosh(双曲余弦值).cosh(x) ⇒ Decimal

x: number|string|Decimal

详情查看 hyperbolicCosine.

a = Decimal.cosh(x)
b = new Decimal(x).cosh()
a.equals(b)                    // true
div(除法).div(x, y) ⇒ Decimal

x: number|string|Decimal
y: number|string|Decimal

详情查看 dividedBy.

a = Decimal.div(x, y)
b = new Decimal(x).div(y)
a.equals(b)                    // true
exp(自然指数).exp(x) ⇒ Decimal

x: number|string|Decimal

详情查看 naturalExponential.

a = Decimal.exp(x)
b = new Decimal(x).exp()
a.equals(b)                    // true
floor(向下取整).floor(x) ⇒ Decimal

x: number|string|Decimal

详情查看 floor.

a = Decimal.floor(x)
b = new Decimal(x).floor()
a.equals(b)                    // true
hypot(欧几里德范数) .hypot([x [, y, ...]]) ⇒ Decimal

x: number|string|Decimal
y: number|string|Decimal

返回所有参数的平方和的平方根, 并使用 rounding(舍入)模式, precision(精确)到有效数字,然后返回一个新的 Decimal对象。

r = Decimal.hypot(x, y)
ln(自然对数).ln(x) ⇒ Decimal

x: number|string|Decimal

详情查看 naturalLogarithm.

a = Decimal.ln(x)
b = new Decimal(x).ln()
a.equals(b)                    // true
isDecimal(是否为Decimal) .isDecimal(object) ⇒ boolean

object: 任意

如果 object 是 Decimal 实例(其中Decimal是任何Decimal构造函数), 则返回true;否则,返回false

a = new Decimal(1)
b = {}
a instanceof Decimal           // true
Decimal.isDecimal(a)           // true
Decimal.isDecimal(b)           // false
log(对数).log(x [, base]) ⇒ Decimal

x: number|string|Decimal
base: number|string|Decimal

详情查看 logarithm.

默认的底数是 10,它与 JavaScript 的 Math.log() 不同,后者返回自然对数(底数e)。

a = Decimal.log(x, y)
b = new Decimal(x).log(y)
a.equals(b)                    // true
log2(2底对数).log2(x) ⇒ Decimal

x: number|string|Decimal

返回 x2 为底的对数, 并使用 rounding(舍入)模式, precision(精确)到有效数字,然后返回一个新的 Decimal对象。

r = Decimal.log2(x)
log10(10底对数).log10(x) ⇒ Decimal

x: number|string|Decimal

返回 x10 为底的对数, 并使用 rounding(舍入)模式, precision(精确)到有效数字,然后返回一个新的 Decimal对象。

r = Decimal.log10(x)
max(最大值).max([x [, y, ...]]) ⇒ Decimal

x: number|string|Decimal
y: number|string|Decimal

返回参数的最大值为一个新的Decimal.

r = Decimal.max(x, y, z)
min(最小值) .min([x [, y, ...]]) ⇒ Decimal

x: number|string|Decimal
y: number|string|Decimal

返回参数的最小值为一个新的Decimal.

r = Decimal.min(x, y, z)
mod(取模).mod(x, y) ⇒ Decimal

x: number|string|Decimal
y: number|string|Decimal

详情查看 modulo.

·
a = Decimal.mod(x, y)
b = new Decimal(x).mod(y)
a.equals(b)                    // true
mul(乘法).mul(x, y) ⇒ Decimal

x: number|string|Decimal
y: number|string|Decimal

详情查看 times.

a = Decimal.mul(x, y)
b = new Decimal(x).mul(y)
a.equals(b)                    // true
noConflict.noConflict() ⇒ Decimal 构造函数

仅限于浏览器.

Decimal 变量恢复为加载该库之前的值,并返回对原始Decimal构造函数的引用,以便可以将其分配给具有不同名称的变量。

<script> Decimal = 1 </script>
<script src='/path/to/decimal.js'></script>
<script>
  a = new Decimal(2)      // '2'
  D = Decimal.noConflict()
  Decimal                 // 1
  b = new D(3)            // '3'
</script>
pow(幂).pow(base, exponent) ⇒ Decimal

base: number|string|Decimal
exponent: number|string|Decimal

详情查看 toPower.

a = Decimal.pow(x, y)
b = new Decimal(x).pow(y)
a.equals(b)                    // true
random(随机数) .random([dp]) ⇒ Decimal

dp: number: integer,包括01e+9

返回一个 大于等于 0,小于1 伪随机数的 Decimal 对象。

返回 dp 位的小数,如果位数不足,直接返回小数位。 如果省略 dp ,小数位数为默认的precision精度设置。

如果当前 Decimal 的构造函数的属性 crypto 的值为 true, 并且 crypto 对象在环境中可用, 则由 crypto.getRandomValues(现代浏览器中的Web密码API) 或者 crypto.randomBytes(Node.js)来生成, 如果 crypto 的属性值为 false, 则返回值由Math.random(最快)生成。

要使 crypto 对象在 Node.js 全局中可用,可以使用:

global.crypto = require('crypto')

如果 crypto 设置为 true , 但是 crypto 对象又不可用,将会抛出异常。

如果使用crypto(加密)方法,则返回的十进制值是加密安全的,并且与随机值在统计上是无法区分的。

Decimal.set({ precision: 10 })
Decimal.random()                    // '0.4117936847'
Decimal.random(20)                  // '0.78193327636914089009'
round(四舍五入).round(x) ⇒ Decimal

x: number|string|Decimal

详情查看 round.

a = Decimal.round(x)
b = new Decimal(x).round()
a.equals(b)                    // true
set(设置).set(object) ⇒ Decimal 构造函数

object: object

为指定的 Decimal 构造函数配置 '全局' 的参数,既对当前创建的 Decimal 实例生效。

Returns: 当前 Decimal 对象的实例.

配置对象 object 可以包含全部或者部分配置,这些属性在 Properties(属性)中有详细描述,以下有示例:

检查配置对象属性的值的有效性,然后将其存储为此Decimal构造函数的同名属性。

如果 object'defaults'true,则所有未指定的属性都将重置为其默认值。

Throws:无效的配置参数.

// 默认值
Decimal.set({
    precision: 20,
    rounding: 4,
    toExpNeg: -7,
    toExpPos: 21,
    maxE: 9e15,
    minE: -9e15,
    modulo: 1,
    crypto: false
})

// 将所有属性重置为其默认值
Decimal.set({ defaults: true })

// 将precision设置为50,并将所有其他属性设置为其默认值
Decimal.set({ precision: 50, defaults: true })

也可以直接使用Decimal构造函数来设置,但是这回跳过参数有效性检查,如果你知道是如何进行有效配置,那么这不是问题。

Decimal.precision = 40
sign(符号函数).sign(x) ⇒ number

x: number|string|Decimal

返回值  
1 x 大于0
-1 x 小于0
0 x 等于正0
-0 x 等于负0
NaN xNaN
r = Decimal.sign(x)
sin(正弦值).sin(x) ⇒ Decimal

x: number|string|Decimal

详情查看 sine.

a = Decimal.sin(x)
b = new Decimal(x).sin()
a.equals(b)                    // true
sinh(双曲正弦值).sinh(x) ⇒ Decimal

x: number|string|Decimal

详情查看 hyperbolicSine.

a = Decimal.sinh(x)
b = new Decimal(x).sinh()
a.equals(b)                    // true
sqrt(平方根).sqrt(x) ⇒ Decimal

x: number|string|Decimal

详情查看 squareRoot.

a = Decimal.sqrt(x)
b = new Decimal(x).sqrt()
a.equals(b)                    // true
sub(减法).sub(x, y) ⇒ Decimal

x: number|string|Decimal
y: number|string|Decimal

详情查看 minus.

a = Decimal.sub(x, y)
b = new Decimal(x).sub(y)
a.equals(b)                    // true
tan(正切值).tan(x) ⇒ Decimal

x: number|string|Decimal

详情查看 tangent.

a = Decimal.tan(x)
b = new Decimal(x).tan()
a.equals(b)                    // true
tanh(双曲正切值).tanh(x) ⇒ Decimal

x: number|string|Decimal

详情查看 hyperbolicTangent.

a = Decimal.tanh(x)
b = new Decimal(x).tanh()
a.equals(b)                    // true
trunc(去除小数).trunc(x) ⇒ Decimal

x: number|string|Decimal

详情查看 truncated.

a = Decimal.trunc(x)
b = new Decimal(x).trunc()
a.equals(b)                    // true

Properties 属性

Decimal 构造函数可配置的属性。

配置属性

使用set方法设置配置属性 precision, rounding, minE, maxE, toExpNeg, toExpPos, modulo, crypto

作为简单的对象属性,可以不使用set来直接设置它们,但是这样会不检查配置值的有效性。例如:

Decimal.set({ precision: 0 })
// '[DecimalError] Invalid argument: precision: 0'

Decimal.precision = 0
// 没有引发错误,这会导致计算结果不准确。
precision(精度)

number: integer, 包含11e+9
默认值: 20

运算结果的最大有效位数.

所有返回Decimal的函数都会将返回值四舍五入为有效的精度(precision)Decimal, absoluteValue, ceil, floor, negated, round, toDecimalPlaces, toNearesttruncated 除外。

有关三角函数的精度请查看 Pi.

Decimal.set({ precision: 5 })
Decimal.precision                  // 5
rounding(舍入)

number: integer, 包含 08
默认值: 4 (ROUND_HALF_UP 向上靠近最近值)

round, toBinary, toDecimalPlaces, toExponential, toFixed, toHexadecimal, toNearest, toOctal, toPrecision, toSignificantDigits 的运算结果使用默认的舍入方式舍入到有效精度precision

舍入模式 rounding modes 可使用构造函数来进行设置。

Decimal.set({ rounding: Decimal.ROUND_UP })
Decimal.set({ rounding: 0 })       // 0 相当于 Decimal.ROUND_UP
Decimal.rounding                   // 0
minE(最小指数)

number: integer, 包括 -9e150
默认值: -9e15

负指数值极限,低于该值会发生下溢至零。

如果 Decimal 要由计算返回的十进制的指数小于 minE ,则该十进制的值将变为零。

JavaScript 对于 -324 以下的指数会下溢至零.

Decimal.set({ minE: -500 })
Decimal.minE                       // -500
new Decimal('1e-500')              // '1e-500'
new Decimal('9.9e-501')            // '0'

Decimal.set({ minE: -3 })
new Decimal(0.001)                 // '0.01'       e 为 -3
new Decimal(0.0001)                // '0'          e 为 -4,下溢至零

Decimal 非零小数的的最小值为:1e-9000000000000000

maxE

number: integer, 包括 09e15
默认值: 9e15

正指数值极限,超过该极限值会发生 Infinity 溢出。

Decimal 如果要由计算返回的十进制的指数大于 maxE,则该十进制的值将变为 Infinity

JavaScript 对于 308 以上的指数会溢出至 Infinity 无穷大.

Decimal.set({ maxE: 500 })
Decimal.maxE                       // 500
new Decimal('9.999e500')           // '9.999e+500'
new Decimal('1e501')               // 'Infinity'

Decimal.set({ maxE: 4 })
new Decimal(99999)                 // '99999'      e 为 4
new Decimal(100000)                // 'Infinity'

Decimal 的有限小数的最大值为:9.999...e+9000000000000000

toExpNeg(负指数值)

number: integer, 包括 -9e150
默认值: -7

在负指数值及其以下的,toString 返回指数表示法。

Decimal.set({ toExpNeg: -7 })
Decimal.toExpNeg                   // -7
new Decimal(0.00000123)            // '0.00000123'       e 为 -6
new Decimal(0.000000123)           // '1.23e-7'

// 始终返回指数表示法:
Decimal.set({ toExpNeg: 0 })

JavaScript 数字对 -7 及以下的负指数使用指数表示法。

不管 toExpNeg 的值如何, toFixed 方法将始终以常规表示法返回值, toExponential 方法将始终以指数形式返回值。

toExpPos(正指数值)

number: integer, 包括 09e15
默认值: 20

大于等于正指数值时 toString 返回指数表示法。

Decimal.set({ toExpPos: 2 })
Decimal.toExpPos                   // 2
new Decimal(12.3)                  // '12.3'        e 为 1
new Decimal(123)                   // '1.23e+2'

// 始终返回指数表示法:
Decimal.set({ toExpPos: 0 })

JavaScript 数字对正指数值大于 20 的值始终使用指数表示。

不管 toExpPos 的值如何, toFixed 方法将始终以常规表示法返回值, toExponential 方法将始终以指数形式返回值。

modulo(模态)

number: integer, 包括 09
默认值: 1 (ROUND_DOWN)

计算模时使用的模式: a mod n.

根据选择的模态模式 modulo 舍入 rounding 计算商 q = a / n

余数 r 的计算方式 r = a - n * q.

下表显示常用的取模/取余模式,但是使用其他模式可能不会提供有用的结果。

属性 描述
ROUND_UP 0 如果被除数为负,则余数为正,否则为负。
ROUND_DOWN 1 使用截断除法,并匹配 JavaScript 余数运算符 % 的行为,余数部分与被除数相同。
ROUND_FLOOR 3 余数部分与除数的符号相同(这与Python的 % 运算符相同)。
ROUND_HALF_EVEN 6 IEEE 754 二进制浮点数算术标准
EUCLID 9 余数永远是正数,欧几里德除法: q = sign(x) * floor(a / abs(x)).

rounding/modulo 模式可在Decimal构造函数处设置。

Decimal.set({ modulo: Decimal.EUCLID })
Decimal.set({ modulo: 9 })         // 9 相当于 Decimal.EUCLID
Decimal.modulo                     // 9
crypto(加密)

boolean: true/false
默认值: false

确定该值是否使用加密安全的伪随机数生成。

详情查看 random.

// Node.js
global.crypto = require('crypto')

Decimal.crypto                     // false
Decimal.set({ crypto: true })
Decimal.crypto                     // true
Rounding modes 舍入模式

舍入模式为 Decimal 构造函数的属性,库本身未在内部引用它们。

舍入模式0到6(包括四舍五入)与Java的BigDecimal类相同。

属性 描述
ROUND_UP 0 远离零
ROUND_DOWN 1 靠近零
ROUND_CEIL 2 靠近正Infinity
ROUND_FLOOR 3 靠近负Infinity
ROUND_HALF_UP 4 向上靠近最近值,如果等距就四舍五入。
ROUND_HALF_DOWN 5 向下靠近最近值,如果等距就舍入为0。
ROUND_HALF_EVEN 6 最近值四舍五入
ROUND_HALF_CEIL 7 最近值靠近+Infinity
ROUND_HALF_FLOOR 8 最近值靠近-Infinity
EUCLID 9 不是舍入模式, 详情查看 modulo
Decimal.set({ rounding: Decimal.ROUND_CEIL })
Decimal.set({ rounding: 2 })       // 2 相当于 Decimal.ROUND_CEIL
Decimal.rounding                   // 2

INSTANCE 实例

Methods 方法

这些方法是从 Decimal 构造函数原型继承下来的。

Decimal 实例不会被其他方法更改.

返回的方法可被链式调用:

x = new Decimal(2).times('999.999999999999999').dividedBy(4).ceil()

方法在执行前不会舍入参数.

±0, ±InfinityNaN 的处理方式和 JavaScript 一致.

有些方法有较短的别名(库内部都是调用较短的别名)。

absoluteValue(绝对值) .abs() ⇒ Decimal

返回一个数的绝对值,不要符号,只要大小,返回一个新的 Decimal 。

precision精度 设置不会对其产生影响。

x = new Decimal(-0.8)
y = x.absoluteValue()         // '0.8'
z = y.abs()                   // '0.8'
ceil(上入整数).ceil() ⇒ Decimal

Infinity 舍入,返回一个新的 Decimal 。

precision精度 设置不会对其产生影响。

x = new Decimal(1.3)
x.ceil()                      // '2'
y = new Decimal(-1.8)
y.ceil()                      // '-1'
comparedTo(对比).cmp(x) ⇒ number

x: number|string|Decimal

返回值  
1 Decimal 的值大于 x
-1 Decimal 的值小于 x
0 Decimal 的值等于 x
NaN Decimal 的值或者x 等于 NaN
x = new Decimal(Infinity)
y = new Decimal(5)
x.comparedTo(y)                // 1
x.comparedTo(x.minus(1))       // 0
y.cmp(NaN)                     // NaN
cosine(余弦值).cos() ⇒ Decimal

计算 Decimal 弧度的余弦值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-Infinity, Infinity]
值范围: [-1, 1]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(0.25)
x.cosine()                      // '0.96891242171064478414'
y = new Decimal(-0.25)
y.cos()                         // '0.96891242171064478414'
cubeRoot(立方根).cbrt() ⇒ Decimal

计算 Decimal 值的立方根(三次方根),按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

返回值会被正常的舍入,也就是说在舍入之前已经计算出无限个小数为。

x = new Decimal(125)
x.cubeRoot()                    // '5'
y = new Decimal(3)
y.cbrt()                        // '1.4422495703074083823'
decimalPlaces(小数位数).dp() ⇒ number

返回小数点后的位数,即小数点后的位数的值。

x = new Decimal(1.234)
x.decimalPlaces()              // '3'
y = new Decimal(987.654321)
y.dp()                         // '6'
dividedBy(除法).div(x) ⇒ Decimal

x: number|string|Decimal

计算 Decimal 值的除以 x,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

x = new Decimal(355)
y = new Decimal(113)
x.dividedBy(y)             // '3.14159292035398230088'
x.div(5)                   // '71'
dividedToIntegerBy(整数除法).divToInt(x) ⇒ Decimal

x: number|string|Decimal

计算 Decimal 值的除以 x,获取整数部分,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

x = new Decimal(5)
y = new Decimal(3)
x.dividedToIntegerBy(y)     // '1'
x.divToInt(0.7)             // '7'
equals(等于).eq(x) ⇒ boolean

x: number|string|Decimal

如果 Decimal 的值等于 x 的值,则返回 true ,否则返回 false。 与JavaScript一样,NaN 不等于 NaN

备注: 此方法内部使用 cmp 实现.

0 === 1e-324                     // true
x = new Decimal(0)
x.equals('1e-324')               // false
new Decimal(-0).eq(x)            // true  ( -0 === 0 )

y = new Decimal(NaN)
y.equals(NaN)                    // false
floor(向下取整).floor() ⇒ Decimal

负Infinity 舍入,保留整数。

precision精度 设置不会对其产生影响。

x = new Decimal(1.8)
x.floor()                   // '1'
y = new Decimal(-1.3)
y.floor()                   // '-2'
greaterThan(大于).gt(x) ⇒ boolean

x: number|string|Decimal

如果 Decimal 的值大于 x 的值,则返回 true ,否则返回 false

备注: 此方法内部使用 cmp 实现.

0.1 > (0.3 - 0.2)                            // true
x = new Decimal(0.1)
x.greaterThan(Decimal(0.3).minus(0.2))       // false
new Decimal(0).gt(x)                         // false
greaterThanOrEqualTo(大于等于).gte(x) ⇒ boolean

x: number|string|Decimal

如果 Decimal 的值大于或者等于 x 的值,则返回 true ,否则返回 false

备注: 此方法内部使用 cmp 实现.

(0.3 - 0.2) >= 0.1                       // false
x = new Decimal(0.3).minus(0.2)
x.greaterThanOrEqualTo(0.1)              // true
new Decimal(1).gte(x)                    // true
hyperbolicCosine(双曲余弦值).cosh() ⇒ Decimal

计算 Decimal 值的双曲余弦值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-Infinity, Infinity]
值范围: [1, Infinity]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(1)
x.hyperbolicCosine()                     // '1.5430806348152437785'
y = new Decimal(0.5)
y.cosh()                                 // '1.1276259652063807852'
hyperbolicSine(双曲正弦值).sinh() ⇒ Decimal

计算 Decimal 值的双曲正弦值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-Infinity, Infinity]
值范围: [-Infinity, Infinity]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(1)
x.hyperbolicSine()                       // '1.1752011936438014569'
y = new Decimal(0.5)
y.sinh()                                 // '0.52109530549374736162'
hyperbolicTangent(双曲正切值).tanh() ⇒ Decimal

计算 Decimal 值的双曲正切值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-Infinity, Infinity]
值范围: [-1, 1]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(1)
x.hyperbolicTangent()                    // '0.76159415595576488812'
y = new Decimal(0.5)
y.tanh()                                 // '0.4621171572600097585'
inverseCosine(反余弦值).acos() ⇒ Decimal

计算 Decimal 值的反余弦值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-1, 1]
值范围: [0, pi]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(0)
x.inverseCosine()                        // '1.5707963267948966192'
y = new Decimal(0.5)
y.acos()                                 // '1.0471975511965977462'
inverseHyperbolicCosine(反双曲余弦值).acosh() ⇒ Decimal

计算 Decimal 值的反双曲余弦值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [1, Infinity]
值范围: [0, Infinity]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(5)
x.inverseHyperbolicCosine()              // '2.2924316695611776878'
y = new Decimal(50)
y.acosh()                                // '4.6050701709847571595'
inverseHyperbolicSine(反双曲正弦值).asinh() ⇒ Decimal

计算 Decimal 值的反双曲正弦值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-Infinity, Infinity]
值范围: [-Infinity, Infinity]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(5)
x.inverseHyperbolicSine()                // '2.3124383412727526203'
y = new Decimal(50)
y.asinh()                                // '4.6052701709914238266'
inverseHyperbolicTangent(反双曲正切值).atanh() ⇒ Decimal

计算 Decimal 值的反双曲正切值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-1, 1]
值范围: [-Infinity, Infinity]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(0.5)
x.inverseHyperbolicTangent()             // '0.5493061443340548457'
y = new Decimal(0.75)
y.atanh()                                // '0.97295507452765665255'
inverseSine(反正弦值).asin() ⇒ Decimal

计算 Decimal 值的反正弦值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-1, 1]
值范围: [-pi/2, pi/2]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(0.5)
x.inverseSine()                          // '0.52359877559829887308'
y = new Decimal(0.75)
y.asin()                                 // '0.84806207898148100805'
inverseTangent(反正切值).atan() ⇒ Decimal

计算 Decimal 值的反正切值,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

取值范围: [-Infinity, Infinity]
值范围: [-pi/2, pi/2]

有关此方法的精度限制,请查看 Pi.

x = new Decimal(0.5)
x.inverseTangent()                       // '0.46364760900080611621'
y = new Decimal(0.75)
y.atan()                                 // '0.6435011087932843868'
isFinite(判断有限数).isFinite() ⇒ boolean

如果这个 Decimal 数是一个有限数,返回true,反之返回false.
一个 Decimal 数的非有限数有NaN, Infinity-Infinity.

x = new Decimal(1)
x.isFinite()                             // true
y = new Decimal(Infinity)
y.isFinite()                             // false

备注: 如果 n <= Number.MAX_VALUE,也可以使用本地方法 isFinite() 进行判断.

isInteger(判断整数).isInt() ⇒ boolean

如果这个 Decimal 是一个整数返回true,反之返回false.

x = new Decimal(1)
x.isInteger()                            // true
y = new Decimal(123.456)
y.isInt()                                // false
isNaN.isNaN() ⇒ boolean

如果这个 Decimal 是一个 NaN 则返回 true ,反之返回 false.

x = new Decimal(NaN)
x.isNaN()                                // true
y = new Decimal('Infinity')
y.isNaN()                                // false

备注: 也可以使用本地的 isNaN().

isNegative(判断负数).isNeg() ⇒ boolean

如果这个 Decimal 是一个负数则返回 true,反之返回 false.

x = new Decimal(-0)
x.isNegative()                           // true
y = new Decimal(2)
y.isNeg                                  // false

备注: 如果n <= -Number.MIN_VALUE 使用的是 n < 0 计算的,也就是说他们得到的结果是一样的.

还要注意,符号零是按照IEEE浮点运算标准实现的 (IEEE 754).

Decimal(0).valueOf()                 // '0'
Decimal(0).isNegative()              // false
Decimal(0).negated().valueOf()       // '-0'
Decimal(0).negated().isNegative()    // true
    
isPositive(判断正数).isPos() ⇒ boolean

如果这个 Decimal 是一个正数则返回 true,反之返回 false.

x = new Decimal(0)
x.isPositive()                           // true
y = new Decimal(-2)
y.isPos                                  // false

备注: 如果 n < 0 使用 n <= -Number.MIN_VALUE 判断.

isZero(判断0).isZero() ⇒ boolean

如果这个 Decimal 是一个 zero 则返回 true,反之返回 false.

x = new Decimal(-0)
x.isZero() && x.isNeg()                  // true
y = new Decimal(Infinity)
y.isZero()                               // false

备注: 如果 n == 0 使用的是 n >= Number.MIN_VALUE.

lessThan(小于).lt(x) ⇒ boolean

x: number|string|Decimal

如果这个 Decimal 小于 x 则返回 true,反之返回 false.

备注: 此方法内部使用 cmp.

(0.3 - 0.2) < 0.1                        // true
x = new Decimal(0.3).minus(0.2)
x.lessThan(0.1)                          // false
new Decimal(0).lt(x)                     // true
lessThanOrEqualTo(小于等于).lte(x) ⇒ boolean

x: number|string|Decimal

如果这个 Decimal 小于或者等于 x 则返回 true,反之返回 false.

备注: 此方法内部使用 cmp.

0.1 <= (0.3 - 0.2)                              // false
x = new Decimal(0.1)
x.lessThanOrEqualTo(Decimal(0.3).minus(0.2))    // true
new Decimal(-1).lte(x)                          // true
logarithm(对数).log(x) ⇒ Decimal

x: number|string|Decimal

计算 Decimal 值以 x 为底的对数,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

备注:如果 x 为10,可以省略不写.

x = new Decimal(1000)
x.logarithm()                            // '3'
y = new Decimal(256)
y.log(2)                                 // '8'

如果进行了舍入,结果的误差为 1 ulp(最后一位的单位).

底数为 2 或者 10 结果是不会产生误差的.

有关此方法可能返回错误舍入结果的情况,请参阅toPower,有关精度限制,请参阅naturalLogarithm

该方法的性能随着位数的增加呈指数级下降.

minus(减法).minus(x) ⇒ Decimal

x: number|string|Decimal

计算 Decimal 值减去 x 的结果,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

0.3 - 0.1                                // 0.19999999999999998
x = new Decimal(0.3)
x.minus(0.1)                             // '0.2'
modulo(取模).mod(x) ⇒ Decimal

x: number|string|Decimal

计算 Decimal 值取 x 的模,按照设置的 rounding(舍入方式)precision(精度), 返回一个新的 Decimal 对象.

The value returned, and in particular its sign, is dependent on the value of the modulo property of this Decimal's constructor. If it is 1 (default value), the result will have the same sign as this Decimal, and it will match that of Javascript's % operator (within the limits of double precision) and BigDecimal's remainder method.

See modulo for a description of the other modulo modes.

1 % 0.9                                  // 0.09999999999999998
x = new Decimal(1)
x.modulo(0.9)                            // '0.1'

y = new Decimal(8)
z = new Decimal(-3)
Decimal.modulo = 1
y.mod(z)                                 // '2'
Decimal.modulo = 3
y.mod(z)                                 // '-1'
naturalExponential.exp() ⇒ Decimal

Returns a new Decimal whose value is the base e (Euler's number, the base of the natural logarithm) exponential of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.

The naturalLogarithm function is the inverse of this function.

x = new Decimal(1)
x.naturalExponential()                   // '2.7182818284590452354'
y = new Decimal(2)
y.exp()                                  // '7.3890560989306502272'

The return value will be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding. (The mathematical result of the exponential function is non-terminating, unless its argument is 0).

The performance of this method degrades exponentially with increasing digits.

naturalLogarithm.ln() ⇒ Decimal

Returns a new Decimal whose value is the natural logarithm of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.

The natural logarithm is the inverse of the naturalExponential function.

x = new Decimal(10)
x.naturalLogarithm()                     // '2.3026'
y = new Decimal('1.23e+30')
y.ln()                                   // '69.28'

The return value will be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding. (The mathematical result of the natural logarithm function is non-terminating, unless its argument is 1).

Internally, this method is dependent on a constant whose value is the natural logarithm of 10. This LN10 variable in the source code currently has a precision of 1025 digits, meaning that this method can accurately calculate up to 1000 digits.

If more than 1000 digits is required then the precision of LN10 will need to be increased to 25 digits more than is required - though, as the time-taken by this method increases exponentially with increasing digits, it is unlikely to be viable to calculate over 1000 digits anyway.

negated.neg() ⇒ Decimal

Returns a new Decimal whose value is the value of this Decimal negated, i.e. multiplied by -1.

The return value is not affected by the value of the precision setting.

x = new Decimal(1.8)
x.negated()                              // '-1.8'
y = new Decimal(-1.3)
y.neg()                                  // '1.3'
plus.plus(x) ⇒ Decimal

x: number|string|Decimal

Returns a new Decimal whose value is the value of this Decimal plus x, rounded to precision significant digits using rounding mode rounding.

0.1 + 0.2                                // 0.30000000000000004
x = new Decimal(0.1)
y = x.plus(0.2)                          // '0.3'
new Decimal(0.7).plus(x).plus(y)         // '1.1'
precision.sd([include_zeros]) ⇒ number

Returns the number of significant digits of the value of this Decimal.

If include_zeros is true or 1 then any trailing zeros of the integer part of a number are counted as significant digits, otherwise they are not.

x = new Decimal(1.234)
x.precision()                            // '4'
y = new Decimal(987000)
y.sd()                                   // '3'
y.sd(true)                               // '6'
round.round() ⇒ Decimal

Returns a new Decimal whose value is the value of this Decimal rounded to a whole number using rounding mode rounding.

To emulate Math.round, set rounding to 7, i.e. ROUND_HALF_CEIL.

Decimal.set({ rounding: 4 })
x = 1234.5
x.round()                                // '1235'

Decimal.rounding = Decimal.ROUND_DOWN
x.round()                                // '1234'
x                                        // '1234.5'
sine.sin() ⇒ Decimal

Returns a new Decimal whose value is the sine of the value in radians of this Decimal, rounded to precision significant digits using rounding mode rounding.

Domain: [-Infinity, Infinity]
Range: [-1, 1]

See Pi for the precision limit of this method.

x = new Decimal(0.5)
x.sine()                                 // '0.47942553860420300027'
y = new Decimal(0.75)
y.sin()                                  // '0.68163876002333416673'
squareRoot.sqrt() ⇒ Decimal

Returns a new Decimal whose value is the square root of this Decimal, rounded to precision significant digits using rounding mode rounding.

The return value will be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding.

This method is much faster than using the toPower method with an exponent of 0.5.

x = new Decimal(16)
x.squareRoot()                           // '4'
y = new Decimal(3)
y.sqrt()                                 // '1.73205080756887729353'
y.sqrt().eq( y.pow(0.5) )                // true
tangent.tan() ⇒ Decimal

Returns a new Decimal whose value is the tangent of the value in radians of this Decimal, rounded to precision significant digits using rounding mode rounding.

Domain: [-Infinity, Infinity]
Range: [-Infinity, Infinity]

See Pi for the precision limit of this method.

x = new Decimal(0.5)
x.tangent()                              // '0.54630248984379051326'
y = new Decimal(0.75)
y.tan()                                  // '0.93159645994407246117'
times.times(x) ⇒ Decimal

x: number|string|Decimal

Returns a new Decimal whose value is the value of this Decimal times x, rounded to precision significant digits using rounding mode rounding.

0.6 * 3                                  // 1.7999999999999998
x = new Decimal(0.6)
y = x.times(3)                           // '1.8'
new Decimal('7e+500').times(y)           // '1.26e+501'
toBinary.toBinary([sd [, rm]]) ⇒ string

sd: number: integer, 0 to 1e+9 inclusive
rm: number: integer, 0 to 8 inclusive

Returns a string representing the value of this Decimal in binary, rounded to sd significant digits using rounding mode rm.

If sd is defined, the return value will use binary exponential notation.

If sd is omitted, the return value will be rounded to precision significant digits.

If rm is omitted, rounding mode rounding will be used.

Throws on an invalid sd or rm value.

x = new Decimal(256)
x.toBinary()                             // '0b100000000'
x.toBinary(1)                            // '0b1p+8'
toDecimalPlaces.toDP([dp [, rm]]) ⇒ Decimal

dp: number: integer, 0 to 1e+9 inclusive
rm: number: integer, 0 to 8 inclusive.

Returns a new Decimal whose value is the value of this Decimal rounded to dp decimal places using rounding mode rm.

If dp is omitted, the return value will have the same value as this Decimal.

If rm is omitted, rounding mode rounding is used.

Throws on an invalid dp or rm value.

x = new Decimal(12.34567)
x.toDecimalPlaces(0)                      // '12'
x.toDecimalPlaces(1, Decimal.ROUND_UP)    // '12.4'

y = new Decimal(9876.54321)
y.toDP(3)                           // '9876.543'
y.toDP(1, 0)                        // '9876.6'
y.toDP(1, Decimal.ROUND_DOWN)       // '9876.5'
toExponential.toExponential([dp [, rm]]) ⇒ string

dp: number: integer, 0 to 1e+9 inclusive
rm: number: integer, 0 to 8 inclusive

Returns a string representing the value of this Decimal in exponential notation rounded using rounding mode rm to dp decimal places, i.e with one digit before the decimal point and dp digits after it.

If the value of this Decimal in exponential notation has fewer than dp fraction digits, the return value will be appended with zeros accordingly.

If dp is omitted, the number of digits after the decimal point defaults to the minimum number of digits necessary to represent the value exactly.

If rm is omitted, rounding mode rounding is used.

Throws on an invalid dp or rm value.

x = 45.6
y = new Decimal(x)
x.toExponential()                        // '4.56e+1'
y.toExponential()                        // '4.56e+1'
x.toExponential(0)                       // '5e+1'
y.toExponential(0)                       // '5e+1'
x.toExponential(1)                       // '4.6e+1'
y.toExponential(1)                       // '4.6e+1'
y.toExponential(1, Decimal.ROUND_DOWN)   // '4.5e+1'
x.toExponential(3)                       // '4.560e+1'
y.toExponential(3)                       // '4.560e+1'
toFixed.toFixed([dp [, rm]]) ⇒ string

dp: number: integer, 0 to 1e+9 inclusive
rm: number: integer, 0 to 8 inclusive

Returns a string representing the value of this Decimal in normal (fixed-point) notation rounded to dp decimal places using rounding mode rm.

If the value of this Decimal in normal notation has fewer than dp fraction digits, the return value will be appended with zeros accordingly.

Unlike Number.prototype.toFixed, which returns exponential notation if a number is greater or equal to 1021, this method will always return normal notation.

If dp is omitted, the return value will be unrounded and in normal notation. This is unlike Number.prototype.toFixed, which returns the value to zero decimal places, but is useful when because of the current toExpNeg or toExpNeg values, toString returns exponential notation.

If rm is omitted, rounding mode rounding is used.

Throws on an invalid dp or rm value.

x = 3.456
y = new Decimal(x)
x.toFixed()                       // '3'
y.toFixed()                       // '3.456'
y.toFixed(0)                      // '3'
x.toFixed(2)                      // '3.46'
y.toFixed(2)                      // '3.46'
y.toFixed(2, Decimal.ROUND_DOWN)  // '3.45'
x.toFixed(5)                      // '3.45600'
y.toFixed(5)                      // '3.45600'
toFraction .toFraction([max_denominator]) ⇒ [Decimal, Decimal]

max_denominator: number|string|Decimal: 1 >= integer < Infinity

Returns an array of two Decimals representing the value of this Decimal as a simple fraction with an integer numerator and an integer denominator. The denominator will be a positive non-zero value less than or equal to max_denominator.

If a maximum denominator is omitted, the denominator will be the lowest value necessary to represent the number exactly.

Throws on an invalid max_denominator value.

x = new Decimal(1.75)
x.toFraction()                       // '7, 4'

pi = new Decimal('3.14159265358')
pi.toFraction()                      // '157079632679,50000000000'
pi.toFraction(100000)                // '312689, 99532'
pi.toFraction(10000)                 // '355, 113'
pi.toFraction(100)                   // '311, 99'
pi.toFraction(10)                    // '22, 7'
pi.toFraction(1)                     // '3, 1'
toHexadecimal.toHex([sd [, rm]]) ⇒ string

sd: number: integer, 0 to 1e+9 inclusive
rm: number: integer, 0 to 8 inclusive

Returns a string representing the value of this Decimal in hexadecimal, rounded to sd significant digits using rounding mode rm.

If sd is defined, the return value will use binary exponential notation.

If sd is omitted, the return value will be rounded to precision significant digits.

If rm is omitted, rounding mode rounding will be used.

Throws on an invalid sd or rm value.

x = new Decimal(256)
x.toHexadecimal()                        // '0x100'
x.toHex(1)                               // '0x1p+8'
toJSON.toJSON() ⇒ string

As valueOf.

toNearest.toNearest(x [, rm]) ⇒ Decimal

x: number|string|Decimal
rm: number: integer, 0 to 8 inclusive

Returns a new Decimal whose value is the nearest multiple of x in the direction of rounding mode rm, or rounding if rm is omitted, to the value of this Decimal.

The return value will always have the same sign as this Decimal, unless either this Decimal or x is NaN, in which case the return value will be also be NaN.

The return value is not affected by the value of the precision setting.

x = new Decimal(1.39)
x.toNearest(0.25)                        // '1.5'

y = new Decimal(9.499)
y.toNearest(0.5, Decimal.ROUND_UP)       // '9.5'
y.toNearest(0.5, Decimal.ROUND_DOWN)     // '9'
toNumber.toNumber() ⇒ number

Returns the value of this Decimal converted to a primitive number.

Type coercion with, for example, JavaScript's unary plus operator will also work, except that a Decimal with the value minus zero will convert to positive zero.

x = new Decimal(456.789)
x.toNumber()                   // 456.789
+x                             // 456.789

y = new Decimal('45987349857634085409857349856430985')
y.toNumber()                   // 4.598734985763409e+34

z = new Decimal(-0)
1 / +z                         // Infinity
1 / z.toNumber()               // -Infinity
toOctal.toOctal([sd [, rm]]) ⇒ string

sd: number: integer, 0 to 1e+9 inclusive
rm: number: integer, 0 to 8 inclusive

Returns a string representing the value of this Decimal in octal, rounded to sd significant digits using rounding mode rm.

If sd is defined, the return value will use binary exponential notation.

If sd is omitted, the return value will be rounded to precision significant digits.

If rm is omitted, rounding mode rounding will be used.

Throws on an invalid sd or rm value.

x = new Decimal(256)
x.toOctal()                              // '0o400'
x.toOctal(1)                             // '0o1p+8'
toPower.pow(x) ⇒ Decimal

x: number|string|Decimal: integer or non-integer

Returns a new Decimal whose value is the value of this Decimal raised to the power x, rounded to precision significant digits using rounding mode rounding.

The performance of this method degrades exponentially with increasing digits. For non-integer exponents in particular, the performance of this method may not be adequate.

Math.pow(0.7, 2)               // 0.48999999999999994
x = new Decimal(0.7)
x.toPower(2)                   // '0.49'
new Decimal(3).pow(-2)         // '0.11111111111111111111'

new Decimal(1217652.23).pow('98765.489305603941')
// '4.8227010515242461181e+601039'

Is the pow function guaranteed to be correctly rounded?

The return value will almost always be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding. If a result is incorrectly rounded the maximum error will be 1 ulp (unit in the last place).

For non-integer and larger exponents this method uses the formula

xy = exp(y*ln(x))

As the mathematical return values of the exp and ln functions are both non-terminating (excluding arguments of 0 or 1), the values of the Decimals returned by the functions as implemented by this library will necessarily be rounded approximations, which means that there can be no guarantee of correct rounding when they are combined in the above formula.

The return value may, depending on the rounding mode, be incorrectly rounded only if the first 15 rounding digits are 15 zeros (and there are non-zero digits following at some point), or 15 nines, or a 5 or 4 followed by 14 nines.

Therefore, assuming the first 15 rounding digits are each equally likely to be any digit, 0-9, the probability of an incorrectly rounded result is less than 1 in 250,000,000,000,000.

An example of incorrect rounding:

Decimal.set({ precision: 20, rounding: 1 })
new Decimal(28).pow('6.166675020000903537297764507632802193308677149')
// 839756321.64088511

As the exact mathematical result begins

839756321.6408851099999999999999999999999999998969466049426031167...

and the rounding mode is set to ROUND_DOWN, the correct return value should be

839756321.64088510999
toPrecision.toPrecision([sd [, rm]]) ⇒ string

sd: number: integer, 1 to 1e+9 inclusive
rm: number: integer, 0 to 8 inclusive

Returns a string representing the value of this Decimal rounded to sd significant digits using rounding mode rm.

If sd is less than the number of digits necessary to represent the integer part of the value in normal (fixed-point) notation, then exponential notation is used.

If sd is omitted, the return value is the same as toString.

If rm is omitted, rounding mode rounding is used.

Throws on an invalid sd or rm value.

x = 45.6
y = new Decimal(x)
x.toPrecision()                          // '45.6'
y.toPrecision()                          // '45.6'
x.toPrecision(1)                         // '5e+1'
y.toPrecision(1)                         // '5e+1'
y.toPrecision(2, Decimal.ROUND_UP)       // '46'
y.toPrecision(2, Decimal.ROUND_DOWN)     // '45'
x.toPrecision(5)                         // '45.600'
y.toPrecision(5)                         // '45.600'
toSignificantDigits.toSD([sd [, rm]]) ⇒ Decimal

sd: number: integer, 1 to 1e+9 inclusive.
rm: number: integer, 0 to 8 inclusive.

Returns a new Decimal whose value is the value of this Decimal rounded to sd significant digits using rounding mode rm.

If sd is omitted, the return value will be rounded to precision significant digits.

If rm is omitted, rounding mode rounding will be used.

Throws on an invalid sd or rm value.

Decimal.set({ precision: 5, rounding: 4 })
x = new Decimal(9876.54321)

x.toSignificantDigits()                          // '9876.5'
x.toSignificantDigits(6)                         // '9876.54'
x.toSignificantDigits(6, Decimal.ROUND_UP)       // '9876.55'
x.toSD(2)                                        // '9900'
x.toSD(2, 1)                                     // '9800'
x                                                // '9876.54321'
toString.toString() ⇒ string

Returns a string representing the value of this Decimal.

If this Decimal has a positive exponent that is equal to or greater than toExpPos, or a negative exponent equal to or less than toExpNeg, then exponential notation will be returned.

x = new Decimal(750000)
x.toString()                             // '750000'
Decimal.set({ toExpPos: 5 })
x.toString()                             // '7.5e+5'

Decimal.set({ precision: 4 })
y = new Decimal('1.23456789')
y.toString()                             // '1.23456789'
truncated.trunc() ⇒ Decimal

Returns a new Decimal whose value is the value of this Decimal truncated to a whole number.

The return value is not affected by the value of the precision setting.

x = new Decimal(123.456)
x.truncated()                            // '123'
y = new Decimal(-12.3)
y.trunc()                                // '-12'
valueOf.valueOf() ⇒ string

As toString, but zero is signed.

x = new Decimal(-0)
x.valueOf()                              // '-0'

Properties

The value of a Decimal is stored in a normalised base 10000000 floating point format.

A Decimal instance is an object with three properties:

Property Description Type Value
d digits number[] Array of integers, each 0 - 1e7, or null
e exponent number Integer, -9e15 to 9e15 inclusive, or NaN
s sign number -1, 1, or NaN

All the properties are best considered to be read-only.

As with JavaScript numbers, the original exponent and fractional trailing zeros of a value are not preserved.

x = new Decimal(0.123)                   // '0.123'
x.toExponential()                        // '1.23e-1'
x.d                                      // [ 1230000 ]
x.e                                      // -1
x.s                                      // 1

y = new Number(-123.4567000e+2)          // '-12345.67'
y.toExponential()                        // '-1.234567e+4'
z = new Decimal('-123.4567000e+2')       // '-12345.67'
z.toExponential()                        // '-1.234567e+4'
z.d                                      // [ 12345, 6700000 ]
z.e                                      // 4
z.s                                      // -1

Zero, NaN and Infinity

The table below shows how ±0, NaN and ±Infinity are stored.

±0 NaN ±Infinity
 d  [0] null null
 e  0 NaN NaN
 s  ±1 NaN ±1
x = new Number(-0)                       // 0
1 / x == -Infinity                       // true

y = new Decimal(-0)
y.d                                      // '0' ( [0].toString() )
y.e                                      //  0
y.s                                      // -1
y.toString()                             // '0'
y.valueOf()                              // '-0'

Errors

The errors that are thrown are generic Error objects whose message property begins with "[DecimalError]".

To determine if an exception is a Decimal Error:

try {
    // ...
} catch (e) {
    if ( e instanceof Error && /DecimalError/.test(e.message) ) {
        // ...
    }
}

Pi

The maximum precision of the trigonometric methods is dependent on the internal value of the constant pi, which is defined as the string PI near the top of the source file.

It has a precision of 1025 digits, meaning that the trigonometric methods can calculate up to just over 1000 digits, but the actual figure depends on the precision of the argument passed to them. To calculate the actual figure use:

maximum_result_precision = 1000 - argument_precision

For example, the following both work fine:
Decimal.set({precision: 991}).tan(123456789)
Decimal.set({precision: 9}).tan(991_digit_number)

as, for each, the result precision plus the argument precision, i.e. 991 + 9 and 9 + 991, is less than or equal to 1000.

If greater precision is required then the value of PI will need to be extended to about 25 digits more than the precision required. The time taken by the methods will then be the limiting factor.

The value can also be shortened to reduce the size of the source file if such high precision is not required.

To get the value of pi:

pi = Decimal.acos(-1)

FAQ

Why are trailing fractional zeros removed from Decimals?

Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the precision of a value. This can be useful but the results of arithmetic operations can be misleading.

x = new BigDecimal("1.0")
y = new BigDecimal("1.1000")
z = x.add(y)                      // 2.1000

x = new BigDecimal("1.20")
y = new BigDecimal("3.45000")
z = x.multiply(y)                 // 4.1400000

To specify the precision of a value is to specify that the value lies within a certain range.

In the first example, x has a value of 1.0. The trailing zero shows the precision of the value, implying that it is in the range 0.95 to 1.05. Similarly, the precision indicated by the trailing zeros of y indicates that the value is in the range 1.09995 to 1.10005.

If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995, and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the range of the result of the addition implied by the precision of its operands is 2.04995 to 2.15005.

The result given by BigDecimal of 2.1000 however, indicates that the value is in the range 2.09995 to 2.10005 and therefore the precision implied by its trailing zeros may be misleading.

In the second example, the true range is 4.122744 to 4.157256 yet the BigDecimal answer of 4.1400000 indicates a range of 4.13999995 to 4.14000005. Again, the precision implied by the trailing zeros may be misleading.

This library, like binary floating point and most calculators, does not retain trailing fractional zeros. Instead, the toExponential, toFixed and toPrecision methods enable trailing zeros to be added if and when required.