bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithm...

README

bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.
npm version npm downloads

Features


- Integers and decimals
- Simple API but full-featured
- Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal
- 8 KB minified and gzipped
- Replicates the toExponential, toFixed, toPrecision and toString methods of JavaScript's Number type
- Includes a toFraction and a correctly-rounded squareRoot method
- Supports cryptographically-secure pseudo-random number generation
- No dependencies
- Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only
- Comprehensive documentation and test set

API

If a smaller and simpler library is required see big.js.
It's less than half the size but only works with decimal numbers and only has half the methods.
It also has fewer configuration options than this library, and does not allow NaN or Infinity.

See also decimal.js, which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits.

Load


The library is the single JavaScript file bignumber.js or ES module bignumber.mjs.

Browser


  1. ``` html
  2. <script src='path/to/bignumber.js'></script>
  3. ```

ES module


  1. ``` html
  2. <script type="module">
  3. import BigNumber from './path/to/bignumber.mjs';
  4. ```

Get a minified version from a CDN:


  1. ``` html
  2. <script src='https://cdn.jsdelivr.net/npm/bignumber.js@9.1.0/bignumber.min.js'></script>
  3. ```


  1. ``` sh
  2. npm install bignumber.js
  3. ```

  1. ``` js
  2. const BigNumber = require('bignumber.js');
  3. ```

ES module


  1. ``` js
  2. import BigNumber from "bignumber.js";
  3. import { BigNumber } from "./node_modules/bignumber.js/bignumber.mjs";
  4. ```


  1. ``` js
  2. import BigNumber from 'https://raw.githubusercontent.com/mikemcl/bignumber.js/v9.1.0/bignumber.mjs';
  3. import BigNumber from 'https://unpkg.com/bignumber.js@latest/bignumber.mjs';
  4. ```

Use


The library exports a single constructor function, [BigNumber](http://mikemcl.github.io/bignumber.js/#bignumber), which accepts a value of type Number, String or BigNumber,

  1. ``` js
  2. let x = new BigNumber(123.4567);
  3. let y = BigNumber('123456.7e-3');
  4. let z = new BigNumber(x);
  5. x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z);      // true
  6. ```

To get the string value of a BigNumber use [toString()](http://mikemcl.github.io/bignumber.js/#toS) or [toFixed()](http://mikemcl.github.io/bignumber.js/#toFix). Using toFixed() prevents exponential notation being returned, no matter how large or small the value.

  1. ``` js
  2. let x = new BigNumber('1111222233334444555566');
  3. x.toString();                       // "1.111222233334444555566e+21"
  4. x.toFixed();                        // "1111222233334444555566"
  5. ```

If the limited precision of Number values is not well understood, it is recommended to create BigNumbers from String values rather than Number values to avoid a potential loss of precision.

In all further examples below, let, semicolons and toString calls are not shown. If a commented-out value is in quotes it means toString has been called on the preceding expression.

  1. ``` js
  2. // Precision loss from using numeric literals with more than 15 significant digits.
  3. new BigNumber(1.0000000000000001)         // '1'
  4. new BigNumber(88259496234518.57)          // '88259496234518.56'
  5. new BigNumber(99999999999999999999)       // '100000000000000000000'

  6. // Precision loss from using numeric literals outside the range of Number values.
  7. new BigNumber(2e+308)                     // 'Infinity'
  8. new BigNumber(1e-324)                     // '0'

  9. // Precision loss from the unexpected result of arithmetic with Number values.
  10. new BigNumber(0.7 + 0.1)                  // '0.7999999999999999'
  11. ```

When creating a BigNumber from a Number, note that a BigNumber is created from a Number's decimal toString() value not from its underlying binary value. If the latter is required, then pass the Number's toString(2) value and specify base 2.

  1. ``` js
  2. new BigNumber(Number.MAX_VALUE.toString(2), 2)
  3. ```

BigNumbers can be created from values in bases from 2 to 36. See [ALPHABET](http://mikemcl.github.io/bignumber.js/#alphabet) to extend this range.

  1. ``` js
  2. a = new BigNumber(1011, 2)          // "11"
  3. b = new BigNumber('zz.9', 36)       // "1295.25"
  4. c = a.plus(b)                       // "1306.25"
  5. ```

Performance is better if base 10 is NOT specified for decimal values. Only specify base 10 when you want to limit the number of decimal places of the input value to the current [DECIMAL_PLACES](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.

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

  1. ``` js
  2. 0.3 - 0.1                           // 0.19999999999999998
  3. x = new BigNumber(0.3)
  4. x.minus(0.1)                        // "0.2"
  5. x                                   // "0.3"
  6. ```

The methods that return a BigNumber can be chained.

  1. ``` js
  2. x.dividedBy(y).plus(z).times(9)
  3. x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue()
  4. ```

Some of the longer method names have a shorter alias.

  1. ``` js
  2. x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3))    // true
  3. x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z))                                   // true
  4. ```

As with JavaScript's Number type, there are [toExponential](http://mikemcl.github.io/bignumber.js/#toE), [toFixed](http://mikemcl.github.io/bignumber.js/#toFix) and [toPrecision](http://mikemcl.github.io/bignumber.js/#toP) methods.

  1. ``` js
  2. x = new BigNumber(255.5)
  3. x.toExponential(5)                  // "2.55500e+2"
  4. x.toFixed(5)                        // "255.50000"
  5. x.toPrecision(5)                    // "255.50"
  6. x.toNumber()                        //  255.5
  7. ```

A base can be specified for [toString](http://mikemcl.github.io/bignumber.js/#toS).

Performance is better if base 10 is NOT specified, i.e. use toString() not toString(10). Only specify base 10 when you want to limit the number of decimal places of the string to the current [DECIMAL_PLACES](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.

  1. ``` js
  2. x.toString(16)                     // "ff.8"
  3. ```

There is a [toFormat](http://mikemcl.github.io/bignumber.js/#toFor) method which may be useful for internationalisation.

  1. ``` js
  2. y = new BigNumber('1234567.898765')
  3. y.toFormat(2)                       // "1,234,567.90"
  4. ```

The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the set or config method of the BigNumber constructor.

The other arithmetic operations always give the exact result.

  1. ``` js
  2. BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })

  3. x = new BigNumber(2)
  4. y = new BigNumber(3)
  5. z = x.dividedBy(y)                        // "0.6666666667"
  6. z.squareRoot()                            // "0.8164965809"
  7. z.exponentiatedBy(-3)                     // "3.3749999995"
  8. z.toString(2)                             // "0.1010101011"
  9. z.multipliedBy(z)                         // "0.44444444448888888889"
  10. z.multipliedBy(z).decimalPlaces(10)       // "0.4444444445"
  11. ```

There is a [toFraction](http://mikemcl.github.io/bignumber.js/#toFr) method with an optional maximum denominator argument

  1. ``` js
  2. y = new BigNumber(355)
  3. pi = y.dividedBy(113)               // "3.1415929204"
  4. pi.toFraction()                     // [ "7853982301", "2500000000" ]
  5. pi.toFraction(1000)                 // [ "355", "113" ]
  6. ```

and [isNaN](http://mikemcl.github.io/bignumber.js/#isNaN) and [isFinite](http://mikemcl.github.io/bignumber.js/#isF) methods, as NaN and Infinity are valid BigNumber values.

  1. ``` js
  2. x = new BigNumber(NaN)                                           // "NaN"
  3. y = new BigNumber(Infinity)                                      // "Infinity"
  4. x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite()        // true
  5. ```

The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.

  1. ``` js
  2. x = new BigNumber(-123.456);
  3. x.c                                 // [ 123, 45600000000000 ]  coefficient (i.e. significand)
  4. x.e                                 // 2                        exponent
  5. x.s                                 // -1                       sign
  6. ```

For advanced usage, multiple BigNumber constructors can be created, each with its own independent configuration.

  1. ``` js
  2. // Set DECIMAL_PLACES for the original BigNumber constructor
  3. BigNumber.set({ DECIMAL_PLACES: 10 })

  4. // Create another BigNumber constructor, optionally passing in a configuration object
  5. BN = BigNumber.clone({ DECIMAL_PLACES: 5 })

  6. x = new BigNumber(1)
  7. y = new BN(1)

  8. x.div(3)                            // '0.3333333333'
  9. y.div(3)                            // '0.33333'
  10. ```

To avoid having to call toString or valueOf on a BigNumber to get its value in the Node.js REPL or when using console.log use

  1. ``` js
  2. BigNumber.prototype[require('util').inspect.custom] = BigNumber.prototype.valueOf;
  3. ```

For further information see the API reference in thedoc directory.

Test


The test/modules directory contains the test scripts for each method.

The tests can be run with Node.js or a browser. For Node.js use

  1. ``` sh
  2. npm test
  3. ```

or

  1. ``` sh
  2. node test/test
  3. ```

To test a single method, use, for example

  1. ``` sh
  2. node test/methods/toFraction
  3. ```

For the browser, open test/test.html.

Minify


To minify using, for example, terser

  1. ``` sh
  2. npm install -g terser
  3. ```

  1. ``` sh
  2. terser big.js -c -m -o big.min.js
  3. ```

Licence


The MIT Licence.

See LICENCE.