decimal.js

An arbitrary-precision Decimal type for JavaScript.JavaScript的任意精度Decimal类型。

Hosted on GitHub.

API

See the README on GitHub for a quick-start introduction.请参阅GitHub上的README以获得快速入门介绍。

In all examples below, var and semicolons are not shown, and if a commented-out value is in quotes it means toString has been called on the preceding expression.在下面的所有示例中,没有显示var和分号,如果注释掉的值用引号括起来,则表示前面的表达式调用了toString


When the library is loaded, it defines a single function object, Decimal, the constructor of Decimal instances.加载库时,它定义了一个函数对象Decimal,即Decimal实例的构造函数。

If necessary, multiple Decimal constructors can be created, each with their own independent configuration, e.g. precision and range, which applies to all Decimal instances created from it.如果需要,可以创建多个Decimal构造函数,每个构造函数都有自己的独立配置,例如精度和范围,这适用于从中创建的所有Decimal实例。

A new Decimal constructor is created by calling the clone method of an already existing Decimal constructor.通过调用已存在的Decimal构造函数的clone方法创建新的Decimal构造函数。

CONSTRUCTOR构造函数

DecimalDecimal(value) ⇒ Decimal
value: number|string|Decimal
A legitimate value is an integer or float, including ±0, or is ±Infinity, or NaN.合法value是整数或浮点,包括±0或是±InfinityNaN
The number of digits of value is not limited, except by JavaScript's maximum array size and, in practice, the processing time required.value的位数没有限制,除了JavaScript的最大数组大小和实际需要的处理时间。
The allowable range of value is defined in terms of a maximum exponent, see maxE, and a minimum exponent, see minE.允许的值范围根据最大指数(见maxE)和最小指数(见minE)定义。
As well as in decimal, a string value may be expressed in binary, hexadecimal or octal, if the appropriate prefix is included: 0x or 0X for hexadecimal, 0b or 0B for binary, and 0o or 0O for octal.除了十进制之外,如果包含适当的前缀,字符串value也可以用二进制、十六进制或八进制表示:0x0X表示十六进制,0b0B表示二进制,0o0O表示八进制。
Both decimal and non-decimal string values may use exponential (floating-point), as well as normal (fixed-point) notation.十进制和非十进制字符串值都可以使用指数(浮点)和普通(定点)表示法。
In exponential notation, e or E defines a power-of-ten exponent for decimal values, and p or P defines a power-of-two exponent for non-decimal values, i.e. binary, hexadecimal or octal.在指数表示法中,eE定义十进制值的十次幂,pP定义非十进制值(即二进制、十六进制或八进制)的二次幂。

Returns a new Decimal object instance.返回新的Decimal对象实例。

Throws on an invalid value.引发无效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('0.046_875_000_000')         // '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方法

The methods of a Decimal constructor.Decimal构造函数的方法。

abs.abs(x) ⇒ Decimal

x: number|string|Decimal

See absoluteValue.请参见absoluteValue

a = Decimal.abs(x)
b = new Decimal(x).abs()
a.equals(b)                    // true
acos.acos(x) ⇒ Decimal

x: number|string|Decimal

See inverseCosine.请参见inverseCosine

a = Decimal.acos(x)
b = new Decimal(x).acos()
a.equals(b)                    // true
acosh.acosh(x) ⇒ Decimal

x: number|string|Decimal

See inverseHyperbolicCosine.请参见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

See plus.请参见plus

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

x: number|string|Decimal

See inverseSine.请参见inverseSine

a = Decimal.asin(x)
b = new Decimal(x).asin()
a.equals(b)                    // true
asinh.asinh(x) ⇒ Decimal

x: number|string|Decimal

See inverseHyperbolicSine.请参见inverseHyperbolicSine

a = Decimal.asinh(x)
b = new Decimal(x).asinh()
a.equals(b)                    // true
atan.atan(x) ⇒ Decimal

x: number|string|Decimal

See inverseTangent.请参见inverseTangent

a = Decimal.atan(x)
b = new Decimal(x).atan()
a.equals(b)                    // true
atanh.atanh(x) ⇒ Decimal

x: number|string|Decimal

See inverseHyperbolicTangent.请参见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

Returns a new Decimal whose value is the inverse tangent in radians of the quotient of y and x, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为yx的商的反切线(以弧度为单位),使用舍入模式roundingprecision位有效数字。

The signs of y and x are used to determine the quadrant of the result.yx的符号用于确定结果的象限。

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

See Pi and Math.atan2().请参见PiMath.atan2()

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

x: number|string|Decimal

See cubeRoot.请参见cubeRoot

a = Decimal.cbrt(x)
b = new Decimal(x).cbrt()
a.equals(b)                    // true
ceil.ceil(x) ⇒ Decimal

x: number|string|Decimal

See ceil.请参见ceil

a = Decimal.ceil(x)
b = new Decimal(x).ceil()
a.equals(b)                    // true
clamp.clamp(min, max) ⇒ Decimal

min: number|string|Decimal
max: number|string|Decimal

See clampedTo.请参见clampedTo

Decimal.clamp(10.1, 0, 10)     // '10'
clone .clone([object]) ⇒ Decimal constructor

object: object

Returns a new independent Decimal constructor with configuration settings as described by object (see set), or with the same settings as this Decimal constructor if object is omitted.返回一个新的独立Decimal构造函数,其配置设置如object所述(请参见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 }) is equivalent to:
Decimal9 = Decimal.clone()
Decimal9.set({ precision: 9 })

If object has a 'defaults' property with value true then the new constructor will use the default configuration.如果object具有值为true'defaults'属性,则新构造函数将使用默认配置。

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

// Use the defaults except for precision
D2 = Decimal.clone({ defaults: true, precision: 50 })

It is not inefficient in terms of memory usage to use multiple Decimal constructors as functions are shared between them.在内存使用方面,使用多个Decimal构造函数并不是低效的,因为函数是在它们之间共享的。

cos.cos(x) ⇒ Decimal

x: number|string|Decimal

See cosine.请参见cosine

a = Decimal.cos(x)
b = new Decimal(x).cos()
a.equals(b)                    // true
cosh.cosh(x) ⇒ Decimal

x: number|string|Decimal

See hyperbolicCosine.请参见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

See dividedBy.请参见dividedBy

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

x: number|string|Decimal

See naturalExponential.请参见naturalExponential

a = Decimal.exp(x)
b = new Decimal(x).exp()
a.equals(b)                    // true
floor.floor(x) ⇒ Decimal

x: number|string|Decimal

See floor.请参见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

Returns a new Decimal whose value is the square root of the sum of the squares of the arguments, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为参数平方和的平方根,使用舍入模式roundingprecision位有效数字。

r = Decimal.hypot(x, y)
ln.ln(x) ⇒ Decimal

x: number|string|Decimal

See naturalLogarithm.请参见naturalLogarithm

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

object: any

Returns true if object is a Decimal instance (where Decimal is any Decimal constructor), or false if it is not.如果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

See logarithm.请参见logarithm

The default base is 10, which is not the same as JavaScript's Math.log(), which returns the natural logarithm (base e).默认基数为10,这与JavaScript的Math.log()不同,后者返回自然对数(基数e)。

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

x: number|string|Decimal

Returns a new Decimal whose value is the base 2 logarithm of x, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为x的底2对数,使用舍入模式roundingprecision位有效数字。

r = Decimal.log2(x)
log10.log10(x) ⇒ Decimal

x: number|string|Decimal

Returns a new Decimal whose value is the base 10 logarithm of x, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为x的底10对数,使用舍入模式roundingprecision位有效数字。

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

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

Returns a new Decimal whose value is the maximum of the arguments.返回一个新的Decimal,其值是arguments的最大值。

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

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

Returns a new Decimal whose value is the minimum of the arguments.返回一个新的Decimal,其值为arguments的最小值。

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

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

See modulo.请参见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

See times.请参见times

a = Decimal.mul(x, y)
b = new Decimal(x).mul(y)
a.equals(b)                    // true
noConflict.noConflict() ⇒ Decimal constructor

Browsers only.

Reverts the Decimal variable to the value it had before this library was loaded and returns a reference to the original Decimal constructor so it can be assigned to a variable with a different name.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

See toPower.

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

dp: number: integer, 0 to 1e+9 inclusive:整数,01e+9(含)

Returns a new Decimal with a pseudo-random value equal to or greater than 0 and less than 1.返回伪随机值等于或大于0且小于1的新Decimal。

The return value will have dp decimal places (or less if trailing zeros are produced). 返回值将具有dp个小数点(如果产生尾随零,则小于dp)。If dp is omitted then the number of decimal places will default to the current precision setting.如果省略dp,则小数位数将默认为当前precision设置。

If the value of this Decimal constructor's crypto property is true, and the crypto object is available globally in the host environment, the random digits of the return value are generated by either crypto.getRandomValues (Web Cryptography API in modern browsers) or crypto.randomBytes (Node.js), otherwise, if the the value of the property is false the return value is generated by Math.random (fastest).如果此Decimal构造函数的crypto属性的值为true,并且crypto对象在主机环境中全局可用,则返回值的随机数字由crypto.getRandomValues(现代浏览器中的Web Cryptography API)或crypto.randomBytes(Node.js)生成,否则,如果属性的值为false,则返回值由Math.random(最快)生成。

To make the crypto object available globally in Node.js use要使crypto对象在Node.js中全局可用,请使用

global.crypto = require('crypto')

If the value of this Decimal constructor's crypto property is set true and the crypto object and associated method are not available, an exception will be thrown.如果此Decimal构造函数的crypto属性的值设置为true,并且crypto对象和关联方法不可用,则将引发异常。

If one of the crypto methods is used, the value of the returned Decimal should be cryptographically-secure and statistically indistinguishable from a random value.如果使用了其中一种crypto方法,返回的Decimal值应该是加密安全的,并且在统计上与随机值不可区分。

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

x: number|string|Decimal

See round.请参见round

a = Decimal.round(x)
b = new Decimal(x).round()
a.equals(b)                    // true
set.set(object) ⇒ Decimal constructor

object: object

Configures the 'global' settings for this particular Decimal constructor, i.e. the settings which apply to operations performed on the Decimal instances created by it.为此特定的Decimal构造函数配置“全局”设置,即应用于对其创建的Decial实例执行的操作的设置。

Returns this Decimal constructor.返回此Decimal构造函数。

The configuration object, object, can contain some or all of the properties described in detail at Properties and shown in the example below.配置对象object可以包含Properties中详细描述的部分或全部属性,如下面的示例所示。

The values of the configuration object properties are checked for validity and then stored as equivalently-named properties of this Decimal constructor.检查配置对象属性的值的有效性,然后将其存储为此Decimal构造函数的同名属性。

If object has a 'defaults' property with value true then any unspecified properties will be reset to their default values.如果object具有值为true'defaults'属性,则任何未指定的属性都将重置为其默认值。

Throws on an invalid object or configuration property value.引发无效的object或配置属性值。

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

// Reset all properties to their default values将所有属性重置为其默认值
Decimal.set({ defaults: true })

// Set precision to 50 and all other properties to their default values将精度设置为50,并将所有其他属性设置为其默认值
Decimal.set({ precision: 50, defaults: true })

The properties of a Decimal constructor can also be set by direct assignment, but that will by-pass the validity checking that this method performs - this is not a problem if the user knows that the assignment is valid.Decimal构造函数的属性也可以通过直接赋值来设置,但这将绕过此方法执行的有效性检查-如果用户知道赋值有效,这不是问题。

Decimal.precision = 40
sign.sign(x) ⇒ number

x: number|string|Decimal

Returns返回值 
1 if the value of x is non-zero and its sign is positive如果x的值为非零且其符号为正
-1 if the value of x is non-zero and its sign is negative如果x的值为非零且其符号为负
0 if the value of x is positive zero如果x的值为正零
-0 if the value of x is negative zero如果x的值为负0
NaN if the value of x is NaN如果x的值是NaN
r = Decimal.sign(x)
sin.sin(x) ⇒ Decimal

x: number|string|Decimal

See sine.请参见sine

a = Decimal.sin(x)
b = new Decimal(x).sin()
a.equals(b)                    // true
sinh.sinh(x) ⇒ Decimal

x: number|string|Decimal

See hyperbolicSine.请参见hyperbolicSine

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

x: number|string|Decimal

See squareRoot.请参见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

See minus.请参见minus

a = Decimal.sub(x, y)
b = new Decimal(x).sub(y)
a.equals(b)                    // true
sum.sum(x [, y, ...]) ⇒ Decimal

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

Returns a new Decimal whose value is the sum of the arguments, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为arguments之和,使用舍入模式roundingprecision位有效数字。
Only the result is rounded, not the intermediate summations.只有结果是四舍五入的,而不是中间的总和。

x = 5
y = '16'
z = new Decimal(-11)
Decimal.sum(x, y, z)           // '10'
tan.tan(x) ⇒ Decimal

x: number|string|Decimal

See tangent.请参见tangent

a = Decimal.tan(x)
b = new Decimal(x).tan()
a.equals(b)                    // true
tanh.tanh(x) ⇒ Decimal

x: number|string|Decimal

See hyperbolicTangent.请参见hyperbolicTangent

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

x: number|string|Decimal

See truncated.请参见truncated

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

Properties属性

The properties of a Decimal constructor.Decimal构造函数的属性。

Configuration properties配置属性

The values of the configuration properties precision, rounding, minE, maxE, toExpNeg, toExpPos, modulo, and crypto are set using the set method.使用set方法设置配置属性precisionroundingminEmaxEtoExpNegtoExpPosmodulocrypto的值。

As simple object properties they can be set directly without using set, and it is fine to do so, but the values assigned will not then be checked for validity. For example:作为简单的对象属性,可以不使用set直接设置它们,这样做很好,但分配的值将不会被检查有效性。例如:

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

Decimal.precision = 0
// No error is thrown and the results of calculations are unreliable不会抛出错误,计算结果不可靠
precision

number: integer, 1 to 1e+9 inclusive整数,11e+9(含)
Default value: 默认值:20

The maximum number of significant digits of the result of an operation.运算结果的最大有效位数。

All functions which return a Decimal will round the return value to precision significant digits except Decimal, absoluteValue, ceil, clampedTo, floor, negated, round, toDecimalPlaces, toNearest and truncated.除了DecimalabsoluteValueceilclampedTofloornegatedroundtoDecimalPlacestoNearesttruncated之外,所有返回Decimall的函数都将返回值四舍五入为精确有效数字。

See Pi for the precision limit of the trigonometric methods.三角法的精度极限见Pi

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

number: integer, 0 to 8 inclusive整数,包括08
Default value: 默认值:4 (ROUND_HALF_UP)

The default rounding mode used when rounding the result of an operation to precision significant digits, and when rounding the return value of the round, toBinary, toDecimalPlaces, toExponential, toFixed, toHexadecimal, toNearest, toOctal, toPrecision and toSignificantDigits methods.将运算结果舍入为precision位有效数字,以及舍入round值时使用的默认舍入模式,toBinarytoDecimalPlacestoExponentialtoFixedtoHexadecimaltoNearesttoOctaltoPrecisiontoSignificantDigits方法。

The rounding modes are available as enumerated properties of the constructor.舍入模式可用作构造函数的枚举属性。

Decimal.set({ rounding: Decimal.ROUND_UP })
Decimal.set({ rounding: 0 })       // equivalent
Decimal.rounding                   // 0
minE

number: integer, -9e15 to 0 inclusive整数,-9e150(含)
Default value: 默认值:-9e15

The negative exponent limit, i.e. the exponent value below which underflow to zero occurs.负指数极限,即发生下溢为零的指数值。

If the Decimal to be returned by a calculation would have an exponent lower than minE then the value of that Decimal becomes zero. 如果计算返回的Decimal的指数小于minE,则该Decimals的值变为零。

JavaScript numbers underflow to zero for exponents below -324.对于低于-324的指数,JavaScript数字下溢到零。

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.001'       e is -3
new Decimal(0.0001)                // '0'          e is -4

The smallest possible magnitude of a non-zero Decimal is 1e-9000000000000000非零十进制的最小可能大小为1e-900000000000000

maxE

number: integer, 0 to 9e15 inclusive
Default value: 默认值:9e15

The positive exponent limit, i.e. the exponent value above which overflow to Infinity occurs.正指数极限,即指数值,超过该值时会溢出到Infinity

If the Decimal to be returned by a calculation would have an exponent higher than maxE then the value of that Decimal becomes Infinity. 如果计算返回的Decimal的指数高于maxE,则该Decimal的值将变为Infinity

JavaScript numbers overflow to Infinity for exponents above 308.对于高于308的指数,JavaScript数字溢出到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 is 4
new Decimal(100000)                // 'Infinity'

The largest possible magnitude of a finite Decimal is 9.999...e+9000000000000000有限小数的最大可能大小为9.999..e+90000000000000

toExpNeg

number: integer, -9e15 to 0 inclusive:整数,-9e150(含)
Default value: 默认值:-7

The negative exponent value at and below which toString returns exponential notation.toString返回指数表示法的负指数值。

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

// Always return exponential notation:
Decimal.set({ toExpNeg: 0 })

JavaScript numbers use exponential notation for negative exponents of -7 and below.JavaScript数字使用指数表示-7及以下的负指数。

Regardless of the value of toExpNeg, the toFixed method will always return a value in normal notation and the toExponential method will always return a value in exponential form.不管toExpNeg的值是多少,toFixed方法总是返回一个普通表示法的值,而toExponential方法总是返回指数形式的值。

toExpPos

number: integer, 0 to 9e15 inclusive整数,09e15(含)
Default value: 默认值:20

The positive exponent value at and above which toString returns exponential notation.toString返回指数表示法的正指数值。

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

// Always return exponential notation:
Decimal.set({ toExpPos: 0 })

JavaScript numbers use exponential notation for positive exponents of 20 and above.JavaScript数字使用指数表示20及以上的正指数。

Regardless of the value of toExpPos, the toFixed method will always return a value in normal notation and the toExponential method will always return a value in exponential form.无论toExpPos的值是多少,toFixed方法总是以普通符号返回值,而toExponential方法总是以指数形式返回值。

modulo模式

number: integer, 0 to 9 inclusive:整数,09(包括0到9)
Default value: 默认值:1 (ROUND_DOWN)

The modulo mode used when calculating the modulus: a mod n.计算模数时使用的模数模式:a mod n

The quotient, q = a / n, is calculated according to the rounding mode that corresponds to the chosen modulo mode.q=a/n根据对应于所选modulo模式的舍入模式rounding计算。

The remainder, r, is calculated as: r = a - n * q.余数r计算为:r=a-n*q

The modes that are most commonly used for the modulus/remainder operation are shown in the following table. 模数/余数运算最常用的模式如下表所示。Although the other rounding modes can be used, they may not give useful results.尽管可以使用其他舍入模式,但它们可能不会给出有用的结果。

Property属性ValueDescription描述
ROUND_UP0 The remainder is positive if the dividend is negative, else is negative如果股息为负,余数为正,否则为负
ROUND_DOWN1 The remainder has the same sign as the dividend.余数与股息的符号相同。
This uses truncating division and matches the behaviour of JavaScript's remainder operator %.这使用截断除法并匹配JavaScript的余数运算符%的行为。
ROUND_FLOOR3 The remainder has the same sign as the divisor.余数与除数的符号相同。
(This matches Python's % operator)(这与Python的%运算符匹配)
ROUND_HALF_EVEN6 The IEEE 754 remainder functionIEEE 754余数函数
EUCLID9 The remainder is always positive.余数总是正的。
Euclidian division: q = sign(x) * floor(a / abs(x)).欧几里得除法:q = sign(x) * floor(a / abs(x))

The rounding/modulo modes are available as enumerated properties of the Decimal constructor.舍入/模模式可用作Decimal构造函数的枚举属性。

Decimal.set({ modulo: Decimal.EUCLID })
Decimal.set({ modulo: 9 })         // equivalent
Decimal.modulo                     // 9
crypto

boolean: true/false
Default value: 默认值:false

The value that determines whether cryptographically-secure pseudo-random number generation is used.确定是否使用加密安全伪随机数生成的值。

See random.请参见random

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

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

The library's enumerated rounding modes are stored as properties of the Decimal constructor. 库的枚举舍入模式存储为Decimal构造函数的属性。
They are not referenced internally by the library itself.库本身不在内部引用它们。

Rounding modes 0 to 6 (inclusive) are the same as those of Java's BigDecimal class.舍入模式0到6(包括0到6)与Java的BigDecimal类的舍入模式相同。

Property属性ValueDescription描述
ROUND_UP0Rounds away from zero舍入远离零
ROUND_DOWN1Rounds towards zero向零舍入
ROUND_CEIL2Rounds towards Infinity四舍五入到无穷大
ROUND_FLOOR3Rounds towards -Infinity四舍五入-无限
ROUND_HALF_UP4 Rounds towards nearest neighbour.四舍五入到最近的邻居。
If equidistant, rounds away from zero如果等距,则舍入远离零
ROUND_HALF_DOWN5 Rounds towards nearest neighbour.四舍五入到最近的邻居。
If equidistant, rounds towards zero如果等距,则舍入为零
ROUND_HALF_EVEN6 Rounds towards nearest neighbour.四舍五入到最近的邻居。
If equidistant, rounds towards even neighbour如果等距,则向偶数邻居舍入
ROUND_HALF_CEIL7 Rounds towards nearest neighbour.四舍五入到最近的邻居。
If equidistant, rounds towards Infinity如果等距,则向无穷大舍入
ROUND_HALF_FLOOR8 Rounds towards nearest neighbour.四舍五入到最近的邻居。
If equidistant, rounds towards -Infinity如果等距,则向-无穷大舍入
EUCLID9 Not a rounding mode, see modulo非舍入模式,请参阅
Decimal.set({ rounding: Decimal.ROUND_CEIL })
Decimal.set({ rounding: 2 })       // equivalent
Decimal.rounding                   // 2

INSTANCE

Methods方法

The methods inherited by a Decimal instance from its constructor's prototype object.Decimal实例从其构造函数的原型对象继承的方法。

A Decimal instance is immutable in the sense that it is not changed by its methods.Decimal实例是不可变的,因为它不会被其方法更改。

Methods that return a Decimal can be chained返回Decimal的方法可以被链接:

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

Methods do not round their arguments before execution.方法在执行之前不舍入其参数。

The treatment of ±0, ±Infinity and NaN is consistent with how JavaScript treats these values.对待±0±InfinityNaN与JavaScript处理这些值的方式一致。

Many method names have a shorter alias. (Internally, the library always uses the shorter method names.)许多方法名称的别名较短。(在内部,库总是使用较短的方法名。)

absoluteValue.abs() ⇒ Decimal

Returns a new Decimal whose value is the absolute value, i.e. the magnitude, of the value of this Decimal.返回一个新的Decimal,其值为该Decimal值的绝对值,即大小。

The return value is not affected by the value of the precision setting.返回值不受precision设置值的影响。

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

Returns a new Decimal whose value is the value of this Decimal rounded to a whole number in the direction of positive Infinity.返回一个新的Decimal,其值是此Decimals的值,该值在正Infinity方向上舍入为整数。

The return value is not affected by the value of the precision setting.返回值不受precision设置值的影响。

x = new Decimal(1.3)
x.ceil()                      // '2'
y = new Decimal(-1.8)
y.ceil()                      // '-1'
clampedTo.clamp(min, max) ⇒ Decimal

min: number|string|Decimal
max: number|string|Decimal

Returns a new Decimal whose value is the value of this Decimal clamped to the range delineated by min and max.返回一个新的Decimal,其值是该Decimals的值,该值被限制在由minmax限定的范围内。

The return value is not affected by the value of the precision setting.返回值不受precision设置值的影响。

x = new Decimal(5)
min = new Decimal(100)
max = new Decimal(Infinity)
x.clampedTo(min, max)         // '100'
x.clamp(-10, -0.1)            // '-0.1'
comparedTo.cmp(x) ⇒ number

x: number|string|Decimal

Returns返回值 
1 if the value of this Decimal is greater than the value of x如果此Decimal的值大于x的值
-1 if the value of this Decimal is less than the value of x如果此Decimal的值小于x的值
0 if this Decimal and x have the same value如果Decimal和x的值相同
NaN if the value of either this Decimal or x is NaN如果此十进制或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

Returns a new Decimal whose value is the cosine of the value in radians of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为该Decimals的弧度值的余弦,使用舍入模式rounding舍入到precision位有效数字。

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

See Pi for the precision limit of this method.该方法的精度极限见Pi

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

Returns a new Decimal whose value is the cube root of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值是此Decimals的立方根,使用舍入模式rounding.到precision位有效数字。

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.返回值将被正确取整,即取整,就像结果在取整之前首先被计算到无限个正确数字一样。

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

Returns the number of decimal places, i.e. the number of digits after the decimal point, of the value of this Decimal.返回此decimal值的小数位数,即小数点后的位数。

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

x: number|string|Decimal

Returns a new Decimal whose value is the value of this Decimal divided by x, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值是此Decimals的值除以x,使用舍入模式roundingprecision位有效数字。

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

Return a new Decimal whose value is the integer part of dividing this Decimal by x, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值是此Decimals除以x的整数部分,使用舍入模式rounding舍入到precision位有效数字。

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

Returns true if the value of this Decimal equals the value of x, otherwise returns false.如果此Decimal的值等于x的值,则返回true,否则返回false
As with JavaScript, NaN does not equal NaN.与JavaScript一样,NaN不等于NaN

Note: This method uses the cmp method internally.注意:此方法在内部使用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

Returns a new Decimal whose value is the value of this Decimal rounded to a whole number in the direction of negative Infinity.返回一个新的Decimal,其值是此Decimals的值,该值在负无穷方向上舍入为整数。

The return value is not affected by the value of the precision setting.返回值不受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

Returns true if the value of this Decimal is greater than the value of x, otherwise returns false.如果此Decimal的值大于x的值,则返回true,否则返回false

Note: This method uses the cmp method internally.注意:此方法在内部使用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

Returns true if the value of this Decimal is greater than or equal to the value of x, otherwise returns false.如果此Decimal的值大于或等于x的值,则返回true,否则返回false

Note: This method uses the cmp method internally.注意:此方法在内部使用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

Returns a new Decimal whose value is the hyperbolic cosine of the value in radians of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为该Decimals的弧度值的双曲余弦,使用舍入模式roundingprecision位有效数字。

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

See Pi for the precision limit of this method.该方法的精度极限见Pi

x = new Decimal(1)
x.hyperbolicCosine()                     // '1.5430806348152437785'
y = new Decimal(0.5)
y.cosh()                                 // '1.1276259652063807852'
hyperbolicSine.sinh() ⇒ Decimal

Returns a new Decimal whose value is the hyperbolic sine of the value in radians of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为该Decimals的弧度值的双曲正弦,使用舍入模式roundingprecision位有效数字。

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

See Pi for the precision limit of this method.该方法的精度极限见Pi

x = new Decimal(1)
x.hyperbolicSine()                       // '1.1752011936438014569'
y = new Decimal(0.5)
y.sinh()                                 // '0.52109530549374736162'
hyperbolicTangent.tanh() ⇒ Decimal

Returns a new Decimal whose value is the hyperbolic tangent of the value in radians of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为该Decimals的弧度值的双曲正切,使用舍入模式roundingprecision位有效数字。

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

See Pi for the precision limit of this method.该方法的精度极限见Pi

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

Returns a new Decimal whose value is the inverse cosine in radians of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值是此Decimal值的反余弦(弧度),使用舍入模式roundingprecision位有效数字。

Domain: 域:[-1, 1]
Range: [0, pi]

See Pi for the precision limit of this method.该方法的精度极限见Pi

x = new Decimal(0)
x.inverseCosine()                        // '1.5707963267948966192'
y = new Decimal(0.5)
y.acos()                                 // '1.0471975511965977462'
inverseHyperbolicCosine.acosh() ⇒ Decimal

Returns a new Decimal whose value is the inverse hyperbolic cosine in radians of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值是此Decimal值的反双曲余弦(弧度),使用舍入模式roundingprecision位有效数字。

Domain: 域:[1, Infinity]
Range: [0, Infinity]

See Pi for the precision limit of this method.该方法的精度极限见Pi

x = new Decimal(5)
x.inverseHyperbolicCosine()              // '2.2924316695611776878'
y = new Decimal(50)
y.acosh()                                // '4.6050701709847571595'
inverseHyperbolicSine.asinh() ⇒ Decimal

Returns a new Decimal whose value is the inverse hyperbolic sine in radians of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值是此Decimal值的反双曲正弦(以弧度为单位),使用舍入模式rounding舍入到precision位有效数字。

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

See Pi for the precision limit of this method.该方法的精度极限见Pi

x = new Decimal(5)
x.inverseHyperbolicSine()                // '2.3124383412727526203'
y = new Decimal(50)
y.asinh()                                // '4.6052701709914238266'
inverseHyperbolicTangent.atanh() ⇒ Decimal

Returns a new Decimal whose value is the inverse hyperbolic tangent in radians of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值是此Decimal值的反双曲正切(以弧度为单位),使用舍入模式rounding舍入到precision位有效数字。

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

See Pi for the precision limit of this method.该方法的精度极限见Pi

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

Returns a new Decimal whose value is the inverse sine in radians of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值是此Decimal值的反正弦(以弧度为单位),使用舍入模式rounding舍入到precision位有效数字。。

Domain: 域:[-1, 1]
Range: [-pi/2, pi/2]

See Pi for the precision limit of this method.该方法的精度极限见Pi

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

Returns a new Decimal whose value is the inverse tangent in radians of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为该Decimal的值的反切线(弧度),使用舍入模式rounding舍入到precision位有效数字。

Domain: 域:[-Infinity, Infinity]
Range: [-pi/2, pi/2]

See Pi for the precision limit of this method.该方法的精度极限见Pi

x = new Decimal(0.5)
x.inverseTangent()                       // '0.46364760900080611621'
y = new Decimal(0.75)
y.atan()                                 // '0.6435011087932843868'
isFinite.isFinite() ⇒ boolean

Returns true if the value of this Decimal is a finite number, otherwise returns false.如果此Decimal的值是有限数,则返回true,否则返回false
The only possible non-finite values of a Decimal are NaN, Infinity and -Infinity.十进制的唯一可能的非有限值是NaNInfinity-Infinity

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

Returns true if the value of this Decimal is a whole number, otherwise returns false.如果此Decimal的值为整数,则返回true,否则返回false

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

Returns true if the value of this Decimal is NaN, otherwise returns false.如果此Decimal的值为NaN,则返回true,否则返回false

x = new Decimal(NaN)
x.isNaN()                                // true
y = new Decimal('Infinity')
y.isNaN()                                // false
isNegative.isNeg() ⇒ boolean

Returns true if the value of this Decimal is negative, otherwise returns false.如果此Decimal的值为负值,则返回true,否则返回false

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

Note that zero is signed.请注意,零是有符号的。

new Decimal(0).valueOf()                 // '0'
new Decimal(0).isNegative()              // false
new Decimal(0).negated().valueOf()       // '-0'
new Decimal(0).negated().isNegative()    // true
new Decimal(-0).isNegative()             // true
isPositive.isPos() ⇒ boolean

Returns true if the value of this Decimal is positive, otherwise returns false.如果此十进制的值为正,则返回true,否则返回false

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

Returns true if the value of this Decimal is zero or minus zero, otherwise returns false.如果此Decimal的值为零或负零,则返回true,否则返回false

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

x: number|string|Decimal

Returns true if the value of this Decimal is less than the value of x, otherwise returns false.如果此Decimal的值小于x的值,则返回true,否则返回false

Note: This method uses the cmp method internally.注意:此方法在内部使用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

Returns true if the value of this Decimal is less than or equal to the value of x, otherwise returns false.如果此Decimal的值小于或等于x的值,则返回true,否则返回false

Note: This method uses the cmp method internally.注意:此方法在内部使用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

Returns a new Decimal whose value is the base x logarithm of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为该Decimal的值的底x对数,使用舍入模式rounding舍入到precision位有效数字。

If x is omitted, the base 10 logarithm of the value of this Decimal will be returned.如果省略x,将返回此十进制值的以10为底的对数。

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

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).如果结果四舍五入不正确,最大误差为1 ulp(单位在最后一位)。

Logarithms to base 2 or 10 will always be correctly rounded.210为基数的对数将始终正确四舍五入。

See toPower for the circumstances in which this method may return an incorrectly rounded result, and see naturalLogarithm for the precision limit.有关此方法可能返回错误舍入结果的情况,请参阅toPower,有关精度限制,请参阅naturalLogarithm

The performance of this method degrades exponentially with increasing digits.该方法的性能随着数字的增加而呈指数下降。

minus.minus(x) ⇒ Decimal

x: number|string|Decimal

Returns a new Decimal whose value is the value of this Decimal minus x, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为此Decimal-x的值,使用舍入模式rounding舍入到precision位有效数字。

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

Returns a new Decimal whose value is the value of this Decimal modulo x, rounded to precision significant digits using rounding mode rounding.返回一个新的Decimal,其值为该Decimalm模x的值,使用舍入模式rounding舍入到precision位有效数字。

The value returned, and in particular its sign, is dependent on the value of the modulo property of this Decimal's constructor. 返回的值,尤其是其符号,取决于此Decimal构造函数的modulo属性的值。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.如果它是1(默认值),结果将与此Decimal具有相同的符号,并且它将与Javascript的%运算符(在双精度限制内)和BigDecimal的remainder方法匹配。

See modulo for a description of the other modulo modes.有关其他模模式的描述,请参阅modulo

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.返回一个新的十进制,其值为该十进制值的基数e(欧拉数,自然对数的底)指数,使用舍入模式rounding舍入到precision位有效数字。

The naturalLogarithm function is the inverse of this function.naturalLogarithm函数是该函数的逆函数。

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).(指数函数的数学结果是非终止的,除非其参数为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.返回一个新的Decimal,其值为该Decimal的值的自然对数,使用舍入模式rounding舍入到precision位有效数字。

The natural logarithm is the inverse of the naturalExponential function.自然对数是naturalExponential函数的倒数。

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).(自然对数函数的数学结果是非终止的,除非其自变量为1)。

Internally, this method is dependent on a constant whose value is the natural logarithm of 10. 在内部,该方法依赖于一个常数,其值为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.源代码中的LN10变量目前的精度为1025位,这意味着该方法可以精确计算1000位数字。

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.如果需要超过1000位数字,则需要将LN10的精度提高到所需的25位数字以上-然而,由于该方法所需的时间随着数字的增加呈指数增长,因此无论如何都不可能计算超过1000位。

negated.neg() ⇒ Decimal

Returns a new Decimal whose value is the value of this Decimal negated, i.e. multiplied by -1.返回一个新的Decimal,其值为该Decimals的值,即乘以-1

The return value is not affected by the value of the precision setting.返回值不受precision设置值的影响。

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.返回一个新的Decimal,其值是此Decimal加x的值,使用舍入模式rounding舍入到precision位有效数字。

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.如果include_zerostrue1,则数字整数部分的任何尾随零都将被计算为有效数字,否则不计算。

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.返回一个新的Decimal,其值是使用舍入模式rounding的该Decimal的值。

To emulate Math.round, set rounding to 7, i.e. ROUND_HALF_CEIL.要模拟Math.round,请将rounding设置为7,即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.返回一个新的十进制,其值为该十进制的弧度值的正弦,使用舍入模式rounding舍入到precision位有效数字。

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

See Pi for the precision limit of this method.该方法的精度极限见Pi

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.返回一个新的十进制,其值为该十进制的平方根,使用舍入模式rounding舍入到precision位有效数字。

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.该方法比使用指数为0.5toPower方法快得多。

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.返回一个新的Decimal,其值为该Decimal的弧度值的正切,使用舍入模式rounding舍入到precision位有效数字。

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

See Pi for the precision limit of this method.该方法的精度极限见Pi

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.返回一个新的Decimal,其值是此Decimal乘以x的值,使用舍入模式rounding舍入到precision位有效数字。

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.返回一个字符串,该字符串表示此十进制的值,采用普通(定点)表示法,使用舍入模式rm舍入到dp位小数。

If the value of this Decimal in normal notation has fewer than dp fraction digits, the return value will be appended with zeros accordingly.如果此十进制在正常表示法中的值小于dp小数位数,则返回值将相应地附加零。

Unlike Number.prototype.toFixed, which returns exponential notation if a number is greater or equal to 1021, this method will always return normal notation.Number.prototype.toFixed(如果数字大于或等于1021,则返回指数表示法)不同,该方法将始终返回普通表示法。

If dp is omitted, the return value will be unrounded and in normal notation. 如果省略dp,则返回值将不舍入,并使用普通符号表示。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.这与Number.prototype.toFixed不同,它将值返回到零位小数,但当由于当前的toExpNegtoExpNeg值,toString返回指数表示法时非常有用。

If rm is omitted, rounding mode rounding is used.如果省略rm,则使用舍入模式rounding

Throws on an invalid dp or rm value.引发无效的dprm值。

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.分母将是小于或等于max_dennominator的正非零值。

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.引发无效的max_denominator值。

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.返回一个以十六进制表示此十进制值的字符串,使用舍入模式 将其舍入为sd有效数字。

If sd is defined, the return value will use binary exponential notation.如果定义了sd,则返回值将使用二进制指数表示法。

If sd is omitted, the return value will be rounded to precision significant digits.如果省略sd,返回值将四舍五入为precision位有效数字。

If rm is omitted, rounding mode rounding will be used.如果省略rm,将使用舍入模式rounding

Throws on an invalid sd or rm value.引发无效的sdrm值。

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

As valueOf.作为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.返回一个新的Decimal,其值是取整模式rm方向上x的最近倍数,如果忽略rm,则将其舍入为该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.返回值将始终具有与此Decimal相同的符号,除非此Decimal或xNaN,在这种情况下,返回值也将是NaN

The return value is not affected by the value of the precision setting.返回值不受precision设置值的影响。

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.例如,使用JavaScript的一元加号运算符进行类型强制也会起作用,只是值为负零的十进制将转换为正零。

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.返回一个字符串,表示此十进制的八进制值,使用舍入模式rm将其舍入为sd有效数字。

If sd is defined, the return value will use binary exponential notation.如果定义了sd,则返回值将使用二进制指数表示法。

If sd is omitted, the return value will be rounded to precision significant digits.如果省略sd,返回值将四舍五入为precision位有效数字。

If rm is omitted, rounding mode rounding will be used.如果省略rm,将使用舍入模式rounding

Throws on an invalid sd or rm value.引发无效的sdrm值。

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.返回一个新的Decimal,其值为该Decimal的x次幂,使用舍入模式rounding舍入到precision位有效数字。

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?pow函数是否保证正确取整?

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).如果结果四舍五入不正确,最大误差为1 ulp(单位在最后一位)。

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.由于expln函数的数学返回值都是非终止的(不包括0或1的参数),由该库实现的函数返回的Decimals值必须是四舍五入近似值,这意味着当它们在上述公式中组合时,不能保证正确的四舍五。

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.根据舍入模式的不同,仅当前15位舍入数字是15个零(并且在某个点上有非零数字),或15个9,或54后跟14个9时,返回值可能会被错误舍入。

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.因此,假设前15位四舍五入数字中的每一位都有可能是任何数字0-9,那么错误四舍五进结果的概率小于25000000000000分之1。

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如果舍入模式设置为ROUND_DOWN,则正确的返回值应为

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.返回一个字符串,表示使用舍入模式rm将此十进制值舍入为sd有效数字。

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.如果sd小于表示正常(定点)表示法中数值整数部分所需的位数,则使用指数表示法。

If sd is omitted, the return value is the same as toString.如果省略sd,则返回值与toString相同。

If rm is omitted, rounding mode rounding is used.如果省略rm,则使用舍入模式rounding

Throws on an invalid sd or rm value.引发无效的sdrm值。

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.返回一个新的Decimal,其值是使用舍入模式rm舍入为sd有效数字的该Decimal的值。

If sd is omitted, the return value will be rounded to precision significant digits.如果省略sd,返回值将四舍五入为precision位有效数字。

If rm is omitted, rounding mode rounding will be used.如果省略rm,将使用舍入模式rounding

Throws on an invalid sd or rm value.引发无效的sdrm值。

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.如果此Decimal的正指数等于或大于toExpPos,或负指数等于或小于toExpNeg,则将返回指数表示法。

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.返回一个新的Decimal,其值是此Decimal的值,该值被截断为整数。

The return value is not affected by the value of the precision setting.返回值不受precision设置值的影响。

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.toString一样,但零是有符号的。

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

Properties属性

The value of a Decimal is stored in a normalised base 10000000 floating point format.十进制的值以标准化的基数10000000浮点格式存储。

A Decimal instance is an object with three properties:Decimal实例是一个具有三个属性的对象:

Property属性 Description描述 Type Value
d digits number[] Array of integers, each 0 - 1e7, or null整数数组,每个为0-1e7null
e exponent number Integer, -9e15 to 9e15 inclusive, or NaN整数,-9e159e15(含),或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.与JavaScript数字一样,值的原始指数和小数尾随零不被保留。

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零、NaN和无穷大

The table below shows how ±0, NaN and ±Infinity are stored.下表显示了±0NaN±Infinity被存储。

±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]".引发的错误是message属性以"[DecimalError]"开头的通用Error对象。

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.三角法的最大精度取决于常数pi的内部值,它被定义为源文件顶部附近的字符串PI

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. 它的精度为1025位,这意味着三角法最多可以计算1000位数字,但实际数字取决于传递给它们的参数的精度。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.因为,对于每一个,结果精度加上参数精度,即991+99+991,都小于或等于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. 如果需要更高的精度,则需要将PI值扩展到比所需精度高约25位。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的值:

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. 在第一个示例中,x的值为1.0The trailing zero shows the precision of the value, implying that it is in the range 0.95 to 1.05. 尾随的零表示值的精度,这意味着它在0.951.05的范围内。Similarly, the precision indicated by the trailing zeros of y indicates that the value is in the range 1.09995 to 1.10005.类似地,由y的尾随零表示的精度表示该值在1.099951.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.如果我们将范围内的两个最低值相加,0.95+1.09995=2.04995,如果我们将两个最高值相加1.05+1.10005=2.15005,那么其操作数的精度所暗示的相加结果的范围是2.049952.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.然而,BigDecimal给出的结果为2.1000,表明该值在2.099952.10005之间,因此其尾随零所暗示的精度可能具有误导性。

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. 在第二个示例中,真实范围为4.1227444.157256,而BigDecimal答案为4.1400000表示范围为4.139999954.1400005Again, 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.相反,toExponentialtoFixedtoPrecision方法允许在需要时添加尾随零。