A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.
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.
Load
The library is the single JavaScript file bignumber.js or ES module bignumber.mjs.
Browser
<script src='path/to/bignumber.js'></script>
ES module
<script type="module">
import BigNumber from './path/to/bignumber.mjs';
Get a minified version from a CDN:
<script src='https://cdn.jsdelivr.net/npm/bignumber.js@9.1.2/bignumber.min.js'></script>
npm install bignumber.js
const BigNumber = require('bignumber.js');
ES module
import BigNumber from "bignumber.js";
import { BigNumber } from "./node_modules/bignumber.js/bignumber.mjs";
import BigNumber from 'https://raw.githubusercontent.com/mikemcl/bignumber.js/v9.1.2/bignumber.mjs';
import BigNumber from 'https://unpkg.com/bignumber.js@latest/bignumber.mjs';
Use
The library exports a single constructor function, BigNumber
, which accepts a value of type Number, String or BigNumber,
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);
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.
let x = new BigNumber('1111222233334444555566');
x.toString();
x.toFixed();
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.
new BigNumber(1.0000000000000001)
new BigNumber(88259496234518.57)
new BigNumber(99999999999999999999)
new BigNumber(2e+308)
new BigNumber(1e-324)
new BigNumber(0.7 + 0.1)
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.
new BigNumber(Number.MAX_VALUE.toString(2), 2)
BigNumbers can be created from values in bases from 2 to 36. See ALPHABET
to extend this range.
a = new BigNumber(1011, 2)
b = new BigNumber('zz.9', 36)
c = a.plus(b)
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
setting.
A BigNumber is immutable in the sense that it is not changed by its methods.
0.3 - 0.1
x = new BigNumber(0.3)
x.minus(0.1)
x
The methods that return a BigNumber can be chained.
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.
x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3))
x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z))
As with JavaScript's Number type, there are toExponential
, toFixed
and toPrecision
methods.
x = new BigNumber(255.5)
x.toExponential(5)
x.toFixed(5)
x.toPrecision(5)
x.toNumber()
A base can be specified for toString
.
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
setting.
x.toString(16)
There is a toFormat
method which may be useful for internationalisation.
y = new BigNumber('1234567.898765')
y.toFormat(2)
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.
BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })
x = new BigNumber(2)
y = new BigNumber(3)
z = x.dividedBy(y)
z.squareRoot()
z.exponentiatedBy(-3)
z.toString(2)
z.multipliedBy(z)
z.multipliedBy(z).decimalPlaces(10)
There is a toFraction
method with an optional maximum denominator argument
y = new BigNumber(355)
pi = y.dividedBy(113)
pi.toFraction()
pi.toFraction(1000)
and isNaN
and isFinite
methods, as NaN
and Infinity
are valid BigNumber
values.
x = new BigNumber(NaN)
y = new BigNumber(Infinity)
x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite()
The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.
x = new BigNumber(-123.456);
x.c
x.e
x.s
For advanced usage, multiple BigNumber constructors can be created, each with its own independent configuration.
BigNumber.set({ DECIMAL_PLACES: 10 })
BN = BigNumber.clone({ DECIMAL_PLACES: 5 })
x = new BigNumber(1)
y = new BN(1)
x.div(3)
y.div(3)
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
BigNumber.prototype[require('util').inspect.custom] = BigNumber.prototype.valueOf;
For further information see the API reference in the doc 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
npm test
or
node test/test
To test a single method, use, for example
node test/methods/toFraction
For the browser, open test/test.html.
Minify
To minify using, for example, terser
npm install -g terser
terser big.js -c -m -o big.min.js
Licence
The MIT Licence.
See LICENCE.