bignumber.js

GitHub

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic

RAW Doc

CHANGELOG

#### 11.1.5

* 05/07/26
* #409 toFraction returning a sub-optimal rational approximation.

#### 11.1.4

* 16/06/26
* [BUGFIX] #407 Fix toFormat duplicating the fraction when groupSize is 0.

#### 11.1.3

* 05/06/26
* #406 Fix EXPONENTIAL_AT default value documentation.

#### 11.1.2

* 30/05/26
* [BUGFIX] #405 Fix invalid toFormat output for -0.

#### 11.1.1

* 02/05/26
* Docs: fix version number and decimalPlaces API description.

#### 11.1.0

* 30/04/26
* #401 BigNumber.sum: return zero if there are no arguments.
* #352 Add toBigInt method.
* #286 Add fromFormat method.
* #262 decimalPlaces, toFixed and toFormat: support negative decimal places.
* #260 toFormat: support minimum/maximum decimal places.
* toFormat: fallback to FORMAT for each property not in options.
* [BUGFIX] #342 Large DECIMAL_PLACES causing slow hex integer base conversion.
Typescript: add test_api.ts* to improved typed API test coverage.

#### 11.0.0

* 14/04/26
* Add STRICT configuration option:
if true (default), throw an exception on invalid input.
if false, return NaN on invalid input.
* toFraction: return [1, 0] for Infinity and [0, 0] for NaN.
* Support underscores as separators.
* If a base is supplied, reject non-finite values and base prefixes.

#### 10.0.2

* 24/02/26
Reinstate README.md* links.

#### 10.0.1

* 24/02/26
Commit dist* folder.

#### 10.0.0

* 23/02/26
* Implement targeted builds for ES modules, CommonJS, and browser (global assignment).
* Add CI workflow.
* Add type declaration import tests.
* Remove BigNumber.DEBUG, so the behaviour is now always as if it was true:
throw on invalid input instead of returning NaN, and
always validate the c, e, and s properties of objects passed to isBigNumber
* Don't call toString on any arbitrary object passed to the constructor.
* Require a BigNumber value to be a string if a base is also passed.
* Add toObject prototype method which returns a plain object with c, e, and s properties.
Remove .npmignore, as files in package.json is used. Add .gitignore*.
Normalise line endings and add .gitattributes*.
* Add typescript to devDependencies.

#### 9.3.1

* 11/07/25
* [BUGFIX] #388 toPrecision fix.

#### 9.3.0

* 19/04/25
* Refactor type declarations:
Rename bignumber.d.ts to types.d.ts*.
Rename bignumber.d.cts to bignumber.d.ts*.
Add export as namespace to bignumber.d.ts*.
Remove subpath exports from package.json*.
Refactor named export from bignumber.d.mts*.
* #383 Remove ? from static BigNumber and default properties.
Add blank lines after titles in CHANGELOG.md*.

#### 9.2.1

* 08/04/25
* #371 #382 Add BigNumber as named export.

#### 9.2.0

* 03/04/25
* #355 Support BigInt argument.
* #371 Provide separate type definitions for CommonJS and ES modules.
* #374 Correct comparedTo return type.

#### 9.1.2

* 28/08/23
* #354 Amend round to avoid bug in v8 Maglev compiler.
* [BUGFIX] #344 minimum(0, -0) should be -0.

#### 9.1.1

* 04/12/22
#338 [BUGFIX] exponentiatedBy: ensure 0*-n === Infinity for very large n.

#### 9.1.0

* 08/08/22
* #329 Remove import example.
* #277 Resolve lint warnings and add number toString note.
Correct decimalPlaces() return type in bignumber.d.ts*.
* Add ES module global crypto example.
#322 Add exports field to package.json*.
#251 (#308) Amend bignumber.d.ts* to allow instantiating a BigNumber without new.

#### 9.0.2

* 12/12/21
* #250 [BUGFIX] Allow use of user-defined alphabet for base 10.
#295 Remove bignumber.min.js and amend README.md*.
Update .travis.yml and LICENCE.md*.

#### 9.0.1

* 28/09/20
* [BUGFIX] #276 Correct sqrt initial estimate.
Update .travis.yml, LICENCE.md and README.md*.

#### 9.0.0

* 27/05/2019
* For compatibility with legacy browsers, remove Symbol references.

#### 8.1.1

* 24/02/2019
* [BUGFIX] #222 Restore missing var to export BigNumber.
Allow any key in BigNumber.Instance in bignumber.d.ts*.

#### 8.1.0

* 23/02/2019
* [NEW FEATURE] #220 Create a BigNumber using {s, e, c}.
* [NEW FEATURE] isBigNumber: if BigNumber.DEBUG is true, also check that the BigNumber instance is well-formed.
* Remove instanceof checks; just use _isBigNumber to identify a BigNumber instance.
Add _isBigNumber to prototype in bignumber.mjs*.
* Add tests for BigNumber creation from object.
Update API.html*.

#### 8.0.2

* 13/01/2019
* #209 toPrecision without argument should follow toString.
Improve Use section of README*.
* Optimise toString(10).
* Add verson number to API doc.

#### 8.0.1

* 01/11/2018
Rest parameter must be array type in bignumber.d.ts*.

#### 8.0.0

* 01/11/2018
* [NEW FEATURE] Add BigNumber.sum method.
* [NEW FEATURE]toFormat: add prefix and suffix options.
* [NEW FEATURE] #178 Pass custom formatting to toFormat.
* [BREAKING CHANGE] #184 toFraction: return array of BigNumbers not strings.
* [NEW FEATURE] #185 Enable overwrite of valueOf to prevent accidental addition to string.
* #183 Add Node.js crypto requirement to documentation.
* [BREAKING CHANGE] #198 Disallow signs and whitespace in custom alphabet.
* [NEW FEATURE] #188 Implement util.inspect.custom for Node.js REPL.
#170 Make isBigNumber a type guard in bignumber.d.ts*.
* [BREAKING CHANGE] BigNumber.min and BigNumber.max: don't accept an array.
Update .travis.yml*.
Remove bower.json*.

#### 7.2.1

* 24/05/2018
Add browser field to package.json*.

#### 7.2.0

* 22/05/2018
#166 Correct .mjs file. Remove extension from main field in package.json*.

#### 7.1.0

* 18/05/2018
Add module field to package.json for bignumber.mjs*.

#### 7.0.2

* 17/05/2018
* #165 Bugfix: upper-case letters for bases 11-36 in a custom alphabet.
Add note to README* regarding creating BigNumbers from Number values.

#### 7.0.1

* 26/04/2018
* #158 Fix global object variable name typo.

#### 7.0.0

* 26/04/2018
* #143 Remove global BigNumber from typings.
* #144 Enable compatibility with Object.freeze(Object.prototype).
* #148 #123 #11 Only throw on a number primitive with more than 15 significant digits if BigNumber.DEBUG is true.
* Only throw on an invalid BigNumber value if BigNumber.DEBUG is true. Return BigNumber NaN instead.
* #154 exponentiatedBy: allow BigNumber exponent.
#156 Prevent Content Security Policy unsafe-eval* issue.
* toFraction: allow Infinity maximum denominator.
* Comment-out some excess tests to reduce test time.
* Amend indentation and other spacing.

#### 6.0.0

* 26/01/2018
* #137 Implement APLHABET configuration option.
* Remove ERRORS configuration option.
* Remove toDigits method; extend precision method accordingly.
* Remove sround method; extend decimalPlaces method accordingly.
* Remove methods: ceil, floor, and truncated.
* Remove method aliases: add, cmp, isInt, isNeg, trunc, mul, neg and sub.
* Rename methods: shift to shiftedBy, another to clone, toPower to exponentiatedBy, and equals to isEqualTo.
* Rename methods: add is prefix to greaterThan, greaterThanOrEqualTo, lessThan and lessThanOrEqualTo.
* Add methods: multipliedBy, isBigNumber, isPositive, integerValue, maximum and minimum.
* Refactor test suite.
Add CHANGELOG.md*.
Rewrite bignumber.d.ts*.
* Redo API image.

#### 5.0.0

* 27/11/2017
* #81 Don't throw on constructor call without new.

#### 4.1.0

* 26/09/2017
Remove node 0.6 from .travis.yml*.
Add bignumber.mjs*.

#### 4.0.4

* 03/09/2017
Add missing aliases to bignumber.d.ts*.

#### 4.0.3

* 30/08/2017
Add types: bignumber.d.ts*.

#### 4.0.2

* 03/05/2017
* #120 Workaround Safari/Webkit bug.

#### 4.0.1

* 05/04/2017
* #121 BigNumber.default to BigNumber['default'].

#### 4.0.0

* 09/01/2017
* Replace BigNumber.isBigNumber method with isBigNumber prototype property.

#### 3.1.2

* 08/01/2017
* Minor documentation edit.

#### 3.1.1

* 08/01/2017
* Uncomment isBigNumber tests.
* Ignore dot files.

#### 3.1.0

* 08/01/2017
* Add isBigNumber method.

#### 3.0.2

* 08/01/2017
* Bugfix: Possible incorrect value of ERRORS after a BigNumber.another call (due to parseNumeric declaration in outer scope).

#### 3.0.1

* 23/11/2016
* Apply fix for old ipads with % issue, see #57 and #102.
* Correct error message.

#### 3.0.0

* 09/11/2016
* Remove require('crypto') - leave it to the user.
* Add BigNumber.set as BigNumber.config alias.
* Default POW_PRECISION to 0.

#### 2.4.0

* 14/07/2016
* #97 Add exports to support ES6 imports.

#### 2.3.0

* 07/03/2016
* #86 Add modulus parameter to toPower.

#### 2.2.0

* 03/03/2016
* #91 Permit larger JS integers.

#### 2.1.4

* 15/12/2015
* Correct UMD.

#### 2.1.3

* 13/12/2015
* Refactor re global object and crypto availability when bundling.

#### 2.1.2

* 10/12/2015
* Bugfix: window.crypto not assigned to crypto.

#### 2.1.1

* 09/12/2015
* Prevent code bundler from adding crypto shim.

#### 2.1.0

* 26/10/2015
* For valueOf and toJSON, include the minus sign with negative zero.

#### 2.0.8

* 2/10/2015
* Internal round function bugfix.

#### 2.0.6

* 31/03/2015
* Add bower.json. Tweak division after in-depth review.

#### 2.0.5

* 25/03/2015
* Amend README. Remove bitcoin address.

#### 2.0.4

* 25/03/2015
* Critical bugfix #58: division.

#### 2.0.3

* 18/02/2015
* Amend README. Add source map.

#### 2.0.2

* 18/02/2015
* Correct links.

#### 2.0.1

* 18/02/2015
* Add max, min, precision, random, shiftedBy, toDigits and truncated methods.
* Add the short-forms: add, mul, sd, sub and trunc.
* Add an another method to enable multiple independent constructors to be created.
* Add support for the base 2, 8 and 16 prefixes 0b, 0o and 0x.
* Enable a rounding mode to be specified as a second parameter to toExponential, toFixed, toFormat and toPrecision.
* Add a CRYPTO configuration property so cryptographically-secure pseudo-random number generation can be specified.
* Add a MODULO_MODE configuration property to enable the rounding mode used by the modulo operation to be specified.
* Add a POW_PRECISION configuration property to enable the number of significant digits calculated by the power operation to be limited.
* Improve code quality.
* Improve documentation.

#### 2.0.0

* 29/12/2014
* Add dividedToIntegerBy, isInteger and toFormat methods.
* Remove the following short-forms: isF, isZ, toE, toF, toFr, toN, toP, toS.
* Store a BigNumber's coefficient in base 1e14, rather than base 10.
* Add fast path for integers to BigNumber constructor.
* Incorporate the library into the online documentation.

#### 1.5.0

* 13/11/2014
* Add toJSON and decimalPlaces methods.

#### 1.4.1

* 08/06/2014
* Amend README.

#### 1.4.0

* 08/05/2014
* Add toNumber.

#### 1.3.0

* 08/11/2013
* Ensure correct rounding of sqrt in all, rather than almost all, cases.
* Maximum radix to 64.

#### 1.2.1

* 17/10/2013
* Sign of zero when x < 0 and x + (-x) = 0.

#### 1.2.0

* 19/9/2013
* Throw Error objects for stack.

#### 1.1.1

* 22/8/2013
* Show original value in constructor error message.

#### 1.1.0

* 1/8/2013
* Allow numbers with trailing radix point.

#### 1.0.1

* Bugfix: error messages with incorrect method name

#### 1.0.0

* 8/11/2012
* Initial release

---

README

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

[](https://www.npmjs.com/package/bignumber.js)
[](https://www.npmjs.com/package/bignumber.js)
[](https://github.com/MikeMcl/bignumber.js/actions/workflows/ci.yml)

<br />

- Features
- Build
- Load
- Use
- Test
- Minify
- Licence


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

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.

Build

bignumber.js is the single source file, and bignumber.d.ts contains the type declarations for it. The build script, build.js, creates targeted builds in a dist directory for ES module, CommonJS, and browser usage.

To run the build script (requires Node.js ≥ 14.14.0):

bash
npm install
npm run build

or: node build.js

A dist directory will be created containing the following:

| Module format | Distributable | Type declaration |
| --- | --- | --- |
| ES module (ESM) | bignumber.mjs | bignumber.d.mts |
| CommonJS (CJS) | bignumber.cjs | bignumber.d.cts |
| Browser (global) | bignumber.js | bignumber.d.ts |

Load

Browser

html
<script src='dist/bignumber.js'></script>

or, minified from a CDN (Content Delivery Network):

html
<script src='https://cdn.jsdelivr.net/npm/bignumber.js@latest/dist/bignumber.min.js'></script>

ES module

html
<script type="module">
import BigNumber from './dist/bignumber.mjs';
// ...
</script>

or, minified from a CDN:

html
<script type="module">
import BigNumber from 'https://cdn.jsdelivr.net/npm/bignumber.js@latest/+esm'
// ...
</script>

Node.js

bash
npm install bignumber.js

CommonJS

javascript
const BigNumber = require('bignumber.js');

// or, testing from a local repo:
const BigNumber = require('./dist/bignumber.cjs');

ES module

javascript
import BigNumber from 'bignumber.js';

// or
import { BigNumber } from 'bignumber.js';

// or, testing from a local repo:
import { BigNumber } from './dist/bignumber.mjs';

Deno

javascript
// @deno-types="https://raw.githubusercontent.com/MikeMcl/bignumber.js/main/dist/bignumber.d.mts"
import BigNumber from 'https://raw.githubusercontent.com/MikeMcl/bignumber.js/main/dist/bignumber.mjs';

// or
// @deno-types="https://unpkg.com/bignumber.js@latest/dist/bignumber.d.mts"
import { BigNumber } from 'https://unpkg.com/bignumber.js@latest/dist/bignumber.mjs';

Use

The library exports a single constructor function, BigNumber, which accepts a value of type Number, String, BigInt or BigNumber,

javascript
let x = new BigNumber(123.4567);
let y = BigNumber('123456.7e-3');
let z = new BigNumber(x);
x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z); // true

To get the string value of a BigNumber use toString() or toFixed(). Using toFixed() prevents exponential notation being returned, no matter how large or small the value.

javascript
let x = new BigNumber('1_234_567_890_000_000_000_000');
x.toString(); // "1.23456789e+21"
x.toFixed(); // "1234567890000000000000"

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.

javascript
// Precision loss from using numeric literals with more than 15 significant digits.
new BigNumber(1.0000000000000001) // '1'
new BigNumber(88259496234518.57) // '88259496234518.56'
new BigNumber(99999999999999999999) // '100000000000000000000'

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

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

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.

javascript
new BigNumber(Number.MAX_VALUE.toString(2), 2)

BigNumbers can be created from string values in bases from 2 to 36. See ALPHABET to extend this range.

javascript
a = new BigNumber('1011', 2)        // "11"
b = new BigNumber('zz.9', 36) // "1295.25"
c = a.plus(b) // "1306.25"

Explicitly passing base 10 is not recommended as it will cause the slower base conversion path to be used, which is only necessary if an unconventional ALPHABET has been specified.

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

javascript
0.3 - 0.1                           // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1) // "0.2"
x // "0.3"

The methods that return a BigNumber can be chained.

javascript
x.dividedBy(y).plus(z).times(9)
x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue()

Some of the longer method names have a shorter alias.

javascript
x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3))    // true
x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z)) // true

As with JavaScript's Number type, there are toExponential, toFixed and toPrecision methods.

javascript
x = new BigNumber(255.5)
x.toExponential(5) // "2.55500e+2"
x.toFixed(5) // "255.50000"
x.toPrecision(5) // "255.50"
x.toNumber() // 255.5

A base can be specified for toString.

javascript
x.toString(16)                     // "ff.8"

Again, explicitly passing base 10 is not recommended as it will cause the slower base conversion path to be used, which is only necessary if an unconventional ALPHABET has been specified.

There is a toFormat method which may be useful for internationalisation.

javascript
y = new BigNumber('1234567.898765')
y.toFormat({
prefix: '€',
decimalSeparator: ',',
groupSeparator: '.',
decimalPlaces: [0, 2]
}) // "€1.234.567,90"

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.

javascript
BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })

x = new BigNumber(2)
y = new BigNumber(3)
z = x.dividedBy(y) // "0.6666666667"
z.squareRoot() // "0.8164965809"
z.exponentiatedBy(-3) // "3.3749999995"
z.toString(2) // "0.1010101011"
z.multipliedBy(z) // "0.44444444448888888889"
z.multipliedBy(z).decimalPlaces(10) // "0.4444444445"

There is a toFraction method with an optional maximum denominator argument

javascript
y = new BigNumber(355)
pi = y.dividedBy(113) // "3.1415929204"
pi.toFraction() // [ "7853982301", "2500000000" ]
pi.toFraction(1000) // [ "355", "113" ]

and isNaN and isFinite methods, as NaN and Infinity are valid BigNumber values.

javascript
x = new BigNumber(NaN)                                           // "NaN"
y = new BigNumber(Infinity) // "Infinity"
x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true

BigNumber.set({ STRICT: false })
z = new BigNumber('zzz')
z.isNaN() // true

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

javascript
x = new BigNumber(-123.456);
x.c // [ 123, 45600000000000 ] coefficient (i.e. significand)
x.e // 2 exponent
x.s // -1 sign

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

javascript
// Set DECIMAL_PLACES for the original BigNumber constructor
BigNumber.set({ DECIMAL_PLACES: 10 })

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

x = new BigNumber(1)
y = new BN(1)

x.div(3) // '0.3333333333'
y.div(3) // '0.33333'

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

javascript
BigNumber.prototype[require('util').inspect.custom] = BigNumber.prototype.valueOf;

For further information see the API reference in the doc directory.

Test

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

The tests can be run with Node.js or a browser. The tests require the CommonJS distributable, so build before testing:

bash
npm run build
npm test

or: node test/test

To test a single method, use, for example

bash
node test/methods/toFraction

For the browser, open test/test.html.

There are also some old programs in perf that still work and can be useful for testing and cross-checking results over large sets of random inputs.

TypeScript

The test/typescript directory contains TypeScript compilation tests that verify the type declarations and imports work correctly for each module format. Run them with:

bash
npm run typecheck

Minify

To minify using, for example, terser:

bash
npm install terser

Minify the browser/global bundle:

bash
terser dist/bignumber.js -c -m -o dist/bignumber.min.js

Licence

The MIT Licence.

See LICENCE.

---