big.js API
Author: M Mclaughlin

# big.js

A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic.

Hosted on GitHub.

The library is incorporated into this page, so it should be available in the console now.

## API

For brevity, `var`, semicolons and `toString` calls have been omitted in the examples below.

### CONSTRUCTOR

##### Big`Big(n) ⇒ Big`

`n` : number|string|Big : a decimal value

By default, the argument `n` can be a number, string or Big number, but if `Big.strict` is set to `true` an error will be thrown if `n` is not a string or Big number.

Note that primitive numbers are accepted purely as a convenience so that quotes don't need to be typed for numeric literals of up to 15 significant digits, and that a Big number is created from a number's `toString` value rather than from its underlying binary floating point value.

`Infinity`, `NaN` and hexadecimal literal strings, e.g. '0xff', are not valid.

String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9.

String values may be in exponential, as well as normal notation.

There is no limit to the number of digits of a string value (other than that of JavaScript's maximum array size), but the largest recommended exponent magnitude is 1000000.

Returns a new Big number with value `n`.

Throws if `n` is invalid.

Using `new` with Big is optional, but note that if no argument is passed when doing so, or if the argument is `undefined`, then a new Big constructor will be returned rather than a new Big number. See creating additional Big number constructors below.

    x = new Big(9)                       // '9'
    y = new Big(x)                       // '9'
    new Big('5032485723458348569331745.33434346346912144534543')
    new Big('4.321e+4')                  // '43210'
    new Big('-735.0918e-430')            // '-7.350918e-428'
    Big(435.345)                         // '435.345'
    new Big()                            // 'Error: [big.js] Invalid value'
    Big2 = Big()                         // No error, and a new Big constructor is returned

#### Properties

##### DP

number : integer, 0 to 1e+6 inclusive
Default value: `20`

The maximum number of decimal places of the results of operations involving division.
It is relevant only to the `div` and `sqrt` methods, and the `pow` method when the exponent is negative.

The value will be checked for validity when one of the above methods is called.
An error will be thrown if the value is found to be invalid.

    Big.DP = 40

##### RM

number : 0, 1, 2 or 3
Default value: `1`

The rounding mode used in operations involving division and by `round`, `toExponential`, `toFixed` and `toPrecision`.

Property | Value | Description | BigDecimal equivalent
--- | --- | --- | ---
Big.roundDown | 0 | Rounds towards zero. I.e. truncate, no rounding. | ROUND_DOWN
Big.roundHalfUp | 1 | Rounds towards nearest neighbour. If equidistant, rounds away from zero. | ROUND_HALF_UP
Big.roundHalfEven | 2 | Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour. | ROUND_HALF_EVEN
Big.roundUp | 3 | Rounds away from zero. | ROUND_UP

The value will be checked for validity when one of the above methods is called.
An error will be thrown if the value is found to be invalid.

    Big.RM = 0
    Big.RM = Big.roundUp

##### NE

number : integer, -1e+6 to 0 inclusive
Default value: `-7`

The negative exponent value at and below which `toString` returns exponential notation.

    Big.NE = -7
    x = new Big(0.00000123)            // '0.00000123'       e is -6
    x = new Big(0.000000123)           // '1.23e-7'

JavaScript numbers use exponential notation for negative exponents of `-7` and below.

Regardless of the value of `Big.NE`, the `toFixed` method will always return a value in normal notation and the `toExponential` method will always return a value in exponential form.

##### PE

number : integer, 0 to 1e+6 inclusive
Default value: `21`

The positive exponent value at and above which `toString` returns exponential notation.

    Big.PE = 2
    x = new Big(12.3)                  // '12.3'        e is 1
    x = new Big(123)                   // '1.23e+2'

JavaScript numbers use exponential notation for positive exponents of `21` and above.

Regardless of the value of `Big.PE`, the `toFixed` method will always return a value in normal notation and the `toExponential` method will always return a value in exponential form.

##### strict

true|false
Default value: `false`

When set to `true`, an error will be thrown if a primitive number is passed to the Big constructor, or if `valueOf` is called, or if `toNumber` is called on a Big which cannot be converted to a primitive number without a loss of precision.

    Big.strict = true
    x = new Big(1)                    // 'TypeError: [big.js] String expected'
    y = new Big('1.000000000000000000001')
    2 + y                             // 'Error: [big.js] valueOf disallowed'
    y.toNumber()                      // 'Error: [big.js] Imprecise conversion'

    Big.strict = false
    x = new Big(0.1)
    y = new Big('1.000000000000000000001')
    2 + y                             // '21.000000000000000000001'
    y.toNumber()                      // 1

### INSTANCE

#### Methods

The methods inherited by a Big number instance from its constructor's prototype object.

A Big number is immutable in the sense that it is not changed by its methods.

##### abs`.abs() ⇒ Big`

Returns a Big number whose value is the absolute value, i.e. the magnitude, of this Big number.

    x = new Big(-0.8)
    x.abs()                     // '0.8'

##### cmp`.cmp(n) ⇒ number`

`n` : number|string|Big

Returns |
--- | ---
1 | If the value of this Big number is greater than the value of `n`
-1 | If the value of this Big number is less than the value of `n`
0 | If this Big number and `n` have the same value

Throws if `n` is invalid.

    x = new Big(6)
    y = new Big(5)
    x.cmp(y)                   // 1
    y.cmp(x.minus(1))          // 0

##### div`.div(n) ⇒ Big`

`n` : number|string|Big

Returns a Big number whose value is the value of this Big number divided by `n`.

If the result has more fraction digits than is specified by `Big.DP`, it will be rounded to `Big.DP` decimal places using rounding mode `Big.RM`.

Throws if `n` is zero or otherwise invalid.

    x = new Big(355)
    y = new Big(113)
    x.div(y)                   // '3.14159292035398230088'
    Big.DP = 2
    x.div(y)                   // '3.14'
    x.div(5)                   // '71'

##### eq`.eq(n) ⇒ boolean`

`n` : number|string|Big

Returns `true` if the value of this Big number equals the value of `n`, otherwise returns `false`.

Throws if `n` is invalid.

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

##### gt`.gt(n) ⇒ boolean`

`n` : number|string|Big

Returns `true` if the value of this Big number is greater than the value of `n`, otherwise returns `false`.

Throws if `n` is invalid.

    0.1 > 0.3 - 0.2              // true
    x = new Big(0.1)
    x.gt(Big(0.3).minus(0.2))    // false
    Big(0).gt(x)                 // false

##### gte`.gte(n) ⇒ boolean`

`n` : number|string|Big

Returns `true` if the value of this Big number is greater than or equal to the value of `n`, otherwise returns `false`.

Throws if `n` is invalid.

    0.3 - 0.2 >= 0.1               // false
    x = new Big(0.3).minus(0.2)
    x.gte(0.1)                     // true
    Big(1).gte(x)                  // true

##### lt`.lt(n) ⇒ boolean`

`n` : number|string|Big

Returns `true` if the value of this Big number is less than the value of `n`, otherwise returns `false`.

Throws if `n` is invalid.

    0.3 - 0.2 < 0.1                // true
    x = new Big(0.3).minus(0.2)
    x.lt(0.1)                      // false
    Big(0).lt(x)                   // true

##### lte`.lte(n) ⇒ boolean`

`n` : number|string|Big

Returns `true` if the value of this Big number is less than or equal to the value of `n`, otherwise returns `false`.

Throws if `n` is invalid.

    0.1 <= 0.3 - 0.2               // false
    x = new Big(0.1)
    x.lte(Big(0.3).minus(0.2))     // true
    Big(-1).lte(x)                 // true

##### minus`.minus(n) ⇒ Big`

`n` : number|string|Big

Returns a Big number whose value is the value of this Big number minus `n`.

Throws if `n` is invalid.

    0.3 - 0.1                  // 0.19999999999999998
    x = new Big(0.3)
    x.minus(0.1)               // '0.2'

##### mod`.mod(n) ⇒ Big`

`n` : number|string|Big

Returns a Big number whose value is the value of this Big number modulo `n`, i.e. the integer remainder of dividing this Big number by `n`.

The result will have the same sign as this Big number, and it will match that of JavaScript's % operator (within the limits of its precision) and BigDecimal's remainder method.

Throws if `n` is zero or otherwise invalid.

    1 % 0.9                    // 0.09999999999999998
    x = new Big(1)
    x.mod(0.9)                 // '0.1'

##### neg`.neg() ⇒ Big`

Returns a Big number whose value is the value of this Big number negated.

    x = new Big(0.3)
    x.neg()                    // '-0.3'
    x.neg().neg()              // '0.3'

##### plus`.plus(n) ⇒ Big`

`n` : number|string|Big

Returns a Big number whose value is the value of this Big number plus `n`.

Throws if `n` is invalid.

    0.1 + 0.2                  // 0.30000000000000004
    x = new Big(0.1)
    y = x.plus(0.2)            // '0.3'
    Big(0.7).plus(x).plus(y)   // '1.1'

##### pow`.pow(n) ⇒ Big`

`n` : number : integer, -1e+6 to 1e+6 inclusive

Returns a Big number whose value is the value of this Big number raised to the power `n`.

Here, `n` must be a JavaScript number, not a Big number, because only small integers are allowed.

If `n` is negative and the result has more fraction digits than is specified by `Big.DP`, it will be rounded to `Big.DP` decimal places using rounding mode `Big.RM`.

Throws if `n` is invalid.

Note: High value exponents may cause this method to be slow to return.

    Math.pow(0.7, 2)           // 0.48999999999999994
    x = new Big(0.7)
    x.pow(2)                   // '0.49'
    Big.DP = 20
    Big(3).pow(-2)             // '0.11111111111111111111'

    new Big(123.456).pow(1000).toString().length     // 5099
    new Big(2).pow(1e+6)       // Time taken (Node.js): 9 minutes 34 secs.

##### prec`.prec(sd, rm)⇒ Big`

`sd`? : number : integer, 1 to 1e+6 inclusive
`rm`? : number : 0, 1, 2 or 3

Returns a Big number whose value is the value of this Big number rounded to a maximum precision of `sd` significant digits using rounding mode `rm`, or `Big.RM` if `rm` is omitted or undefined.

Throws if `sd` or `rm` is invalid.

    down = 0
    half_up = 1
    x = new Big('9876.54321')
    x.prec(2)                 // '9900'
    x.prec(7)                 // '9876.543'
    x.prec(20)                // '9876.54321'
    x.prec(1, down)           // '9000'
    x.prec(1, half_up)        // '10000'
    x                         // '9876.54321'

##### round`.round(dp, rm) ⇒ Big`

`dp`? : number : integer, -1e+6 to 1e+6 inclusive
`rm`? : number : 0, 1, 2 or 3

Returns a Big number whose value is the value of this Big number rounded using rounding mode `rm` to a maximum of `dp` decimal places, or, if `dp` is negative, to an integer which is a multiple of `10**-dp`.

if `dp` is omitted or is undefined, the return value is the value of this Big number rounded to a whole number.
if `rm` is omitted or is undefined, the current `Big.RM` setting is used.

Throws if `dp` or `rm` is invalid.

    x = 123.45
    Math.round(x)                  // 123

    y = new Big(x)
    y.round()                      // '123'
    y.round(2)                     // '123.45'
    y.round(10)                    // '123.45'
    y.round(1, Big.roundDown)      // '123.4'
    y.round(1, Big.roundHalfUp)    // '123.5'
    y.round(1, Big.roundHalfEven)  // '123.4'
    y.round(1, Big.roundUp)        // '123.5'
    y.round(-1, Big.roundDown)     // '120'
    y.round(-2, Big.roundUp)       // '200'
    y                              // '123.45'

##### sqrt`.sqrt() ⇒ Big`

Returns a Big number whose value is the square root of this Big number.

If the result has more fraction digits than is specified by `Big.DP`, it will be rounded to `Big.DP` decimal places using rounding mode `Big.RM`.

Throws if this Big number is negative.

    x = new Big(16)
    x.sqrt()                   // '4'
    y = new Big(3)
    y.sqrt()                   // '1.73205080756887729353'

##### times`.times(n) ⇒ Big`

`n` : number|string|Big

Returns a Big number whose value is the value of this Big number times `n`.

Throws if `n` is invalid.

    0.6 * 3                    // 1.7999999999999998
    x = new Big(0.6)
    y = x.times(3)             // '1.8'
    Big('7e+500').times(y)     // '1.26e+501'

##### toExponential`.toExponential(dp, rm) ⇒ string`

`dp`? : number : integer, 0 to 1e+6 inclusive
`rm`? : number : 0, 1, 2 or 3

Returns a string representing the value of this Big number in exponential notation to a fixed number of `dp` decimal places.

If the value of this Big number in exponential notation has more digits to the right of the decimal point than is specified by `dp`, the return value will be rounded to `dp` decimal places using rounding mode `rm`.

If the value of this Big number in exponential notation has fewer digits to the right of the decimal point than is specified by `dp`, the return value will be appended with zeros accordingly.

If `dp` is omitted or is undefined, 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 or is undefined, the current `Big.RM` setting is used.

Throws if `dp` or `rm` is invalid.

    x = 45.6
    y = new Big(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, Big.roundDown) // '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+6 inclusive
`rm`? : number : 0, 1, 2 or 3

Returns a string representing the value of this Big number in normal notation to a fixed number of `dp` decimal places.

If the value of this Big number in normal notation has more digits to the right of the decimal point than is specified by `dp`, the return value will be rounded to `dp` decimal places using rounding mode `rm`.

If the value of this Big number in normal notation has fewer fraction digits then is specified by `dp`, 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 or is undefined, the return value is simply the value in normal notation. This is also unlike `Number.prototype.toFixed`, which returns the value to zero decimal places.

if `rm` is omitted or is undefined, the current `Big.RM` setting is used.

Throws if `dp` or `rm` is invalid.

    x = 45.6
    y = new Big(x)
    x.toFixed()                // '46'
    y.toFixed()                // '45.6'
    y.toFixed(0)               // '46'
    x.toFixed(3)               // '45.600'
    y.toFixed(3)               // '45.600'

##### toJSON`.toJSON() ⇒ string`

As `toString`.

    x = new Big('177.7e+457')
    y = new Big(235.4325)
    z = new Big('0.0098074')
    str = JSON.stringify( [x, y, z] )

    JSON.parse(str, function (k, v) { return k === '' ? v : new Big(v) })
    // Returns an array of three Big numbers.

##### toPrecision`.toPrecision(sd, rm) ⇒ string`

`sd`? : number : integer, 1 to 1e+6 inclusive
`rm`? : number : 0, 1, 2 or 3

Returns a string representing the value of this Big number to the specified number of `sd` significant digits.

If the value of this Big number has more digits than is specified by `sd`, the return value will be rounded to `sd` significant digits using rounding mode `rm`.

If the value of this Big number has fewer digits than is specified by `sd`, the return value will be appended with zeros accordingly.

If `sd` is less than the number of digits necessary to represent the integer part of the value in normal notation, exponential notation is used.

If `sd` is omitted or is undefined, the return value is the same as `.toString()`.

if `rm` is omitted or is undefined, the current `Big.RM` setting is used.

Throws if `sd` or `rm` is invalid.

    x = 45.6
    y = new Big(x)
    x.toPrecision()            // '45.6'
    y.toPrecision()            // '45.6'
    x.toPrecision(1)           // '5e+1'
    y.toPrecision(1)           // '5e+1'
    x.toPrecision(5)           // '45.600'
    y.toPrecision(5)           // '45.600'

##### toNumber`.toNumber() ⇒ number`

Returns a primitive number representing the value of this Big number.

    x = new Big('123.45')
    x.toNumber()               // 123.45
    y = new Big('1.0000000000000000001')
    y.toNumber()               // 1

If `Big.strict` is `true` an error will be thrown if `toNumber` is called on a Big number which cannot be converted to a primitive number without a loss of precision.

##### toString`.toString() ⇒ string`

Returns a string representing the value of this Big number.

If this Big number has a positive exponent that is equal to or greater than 21, or a negative exponent equal to or less than -7, exponential notation is returned.

The point at which `toString` returns exponential rather than normal notation can be adjusted by changing the value of `Big.PE` and `Big.NE`. By default, Big numbers correspond to JavaScript's number type in this regard.

    x = new Big('9.99e+20')
    x.toString()               // '999000000000000000000'
    y = new Big('1E21')
    y.toString()               // '1e+21'

##### valueOf`.valueOf() ⇒ string`

As `toString` except the minus sign is included for negative zero.

    x = new Big(-0)
    x.valueOf()                 // '-0'
    x.toString()                // '0'

To prevent accidental usage of Big numbers with arithmetic operators, if `Big.strict` is `true` any explicit or implicit calls to `valueOf` will result in an error.

#### Properties

A Big number is an object with three properties:

Property | Description | Type | Value
--- | --- | --- | ---
c | coefficient* | number`[]` | Array of single digits
e | exponent | number | Integer, -1e+6 to 1e+6 inclusive
s | sign | number | -1 or 1

*significand

The value of a Big number is stored in a normalised decimal floating point format which corresponds to the value's `toExponential` form, with the decimal point to be positioned after the most significant (left-most) digit of the coefficient.

Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are not preserved.

    x = new Big(0.123)                 // '0.123'
    x.toExponential()                  // '1.23e-1'
    x.c                                // '1,2,3'
    x.e                                // -1
    x.s                                // 1

    y = new Number(-123.4567000e+2)    // '-12345.67'
    y.toExponential()                  // '-1.234567e+4'
    z = new Big('-123.4567000e+2')     // '-12345.67'
    z.toExponential()                  // '-1.234567e+4'
    z.c                                // '1,2,3,4,5,6,7'
    z.e                                // 4
    z.s                                // -1

A Big number is mutable in the sense that the value of its properties can be changed.
For example, to rapidly shift a value by a power of 10:

    x = new Big('1234.000')    // '1234'
    x.toExponential()          // '1.234e+3'
    x.c                        // '1,2,3,4'
    x.e                        // 3

    x.e = -5
    x                          // '0.00001234'

If changing the coefficient array directly, which is not recommended, be careful to avoid leading or trailing zeros (unless zero itself is being represented).

Minus zero is a valid Big number value, but like JavaScript numbers the minus sign is not shown by `toString`.

    x = new Number(-0)         // 0
    1 / x == -Infinity         // true

    y = new Big(-0)            // '0'
    y.c                        // '0'    [0].toString()
    y.e                        // 0
    y.s                        // -1

#### Errors

The errors that are thrown are instances of `Error`.
The `message` of the errors always begins with `[big.js]`, for example:

    Error: [big.js] Invalid value

Method(s) | Error message | Thrown on/when
--- | --- | ---
`Big cmp div eq gt gte lt lte minus mod plus times` | Invalid value | Invalid value
String expected | `Big.strict` is `true`
`div` | Division by zero | Division by zero
Invalid decimal places | Invalid `Big.DP`
Invalid rounding mode | Invalid `Big.RM`
`mod` | Division by zero | Modulo zero
`pow` | Invalid exponent | Invalid exponent
Invalid decimal places | Invalid `Big.DP`
Invalid rounding mode | Invalid `Big.RM`
`prec` | Invalid precision | Invalid `sd`
Invalid rounding mode | Invalid `rm`/`Big.RM`
`round` | Invalid decimal places | Invalid `dp`
Invalid rounding mode | Invalid `rm`/`Big.RM`
`sqrt` | No square root | Negative number
Invalid decimal places | Invalid `Big.DP`
Invalid rounding mode | Invalid `Big.RM`
`toExponential` | Invalid decimal places | Invalid `dp`
Invalid rounding mode | Invalid `Big.RM`
`toFixed` | Invalid decimal places | Invalid `dp`
Invalid rounding mode | Invalid `Big.RM`
`toNumber` | Imprecise conversion | `Big.strict` is `true`
`toPrecision` | Invalid precision | Invalid `sd`
Invalid rounding mode | Invalid `Big.RM`
`valueOf` | valueOf disallowed | `Big.strict` is `true`

#### FAQ

###### How can I convert a Big number to a primitive JavaScript number?

See `toNumber`.

###### How can I round a Big number to a specified number of significant digits?

See `prec`.

###### How can I set the decimal places and/or rounding mode for just one operation?

This library uses a global configuration for the decimal places and rounding mode used by division operations, so it is just a matter of altering this as required.

    Big.DP = 10
    y = x.sqrt()
    Big.DP = 0
    Big.RM = 1
    z = x.div(3)

There is also the ability to create separate Big number constructors each with their own particular `DP` and `RM` settings. See below.

Finally, there is the option of safely redefining the relevant prototype method as required. For example, the following would enable a decimal places and rounding mode to be passed to the `div` method.

    Big.prototype.div = (function () {
      const div = Big.prototype.div;
      return function (n, dp, rm) {
        const Big = this.constructor;
        const DP = Big.DP;
        const RM = Big.RM;
        if (dp != undefined) Big.DP = dp;
        if (rm != undefined) Big.RM = rm;
        let result = div.call(this, n);
        Big.DP = DP;
        Big.RM = RM;
        return result;
      }
    })();

    var dp = 10;
    var round_up = 2;
    x = x.div(y, dp, round_up);

###### How can I simultaneously use different decimal places and/or rounding mode settings for different Big numbers?

Multiple Big number constructors can be created each with their own particular `DP` and `RM` settings which apply to all Big numbers created from it.

As shown below, an additional Big number constructor is created by calling an existing Big number constructor without using `new` and without any argument.

    Big10 = Big();

    Big.DP = 3;
    Big10.DP = 10;

    x = Big(5);
    y = Big10(5);

    x.div(3)     // 1.667
    y.div(3)     // 1.6666666667

Big numbers created by different constructors can be used together in operations, and it is the `DP` and `RM` setting of the Big number that an operation is called upon that will apply.

In the interest of memory efficiency, all Big number constructors share the same `prototype` object, so while the `DP` and `RM` (and any other own properties) of a constructor are isolated and untouchable by another, its prototype methods are not.

###### Why are trailing fractional zeros removed from Big numbers?

Many 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.

    // Java's BigDecimal
    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 imply 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 the value 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 get 0.95 + 1.09995 = 2.04995 and if we add the two highest values we get 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 is 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 is 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.