bignumber.js vs big.js vs mathjs vs decimal.js
JavaScript Arbitrary-Precision Libraries
bignumber.jsbig.jsmathjsdecimal.jsSimilar Packages:

JavaScript Arbitrary-Precision Libraries

JavaScript arbitrary-precision libraries are designed to handle numerical calculations with high precision, avoiding the pitfalls of floating-point arithmetic in JavaScript. These libraries are essential for applications that require accurate financial calculations, scientific computations, or any domain where precision is critical. They provide various functionalities for arithmetic operations, rounding, and formatting, ensuring that developers can work with numbers accurately without losing precision due to JavaScript's inherent limitations with floating-point numbers.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
bignumber.js33,269,6596,983465 kB122 days agoMIT
big.js27,594,3915,15758.9 kB910 months agoMIT
mathjs2,218,96215,0039.41 MB17816 days agoApache-2.0
decimal.js07,144284 kB188 months agoMIT

Feature Comparison: bignumber.js vs big.js vs mathjs vs decimal.js

Precision Handling

  • bignumber.js:

    bignumber.js offers arbitrary-precision arithmetic with a focus on performance. It allows for precise calculations with large numbers and includes features for rounding, formatting, and conversion, making it suitable for various applications.

  • big.js:

    big.js provides basic arbitrary-precision arithmetic, allowing for accurate calculations with large numbers. It is designed to handle numbers as strings to maintain precision, but it does not support advanced features like rounding modes or complex mathematical functions.

  • mathjs:

    mathjs provides arbitrary-precision arithmetic along with a wide range of mathematical functions. It allows for precise calculations while also supporting complex numbers, matrices, and statistical functions, making it a versatile choice for mathematical applications.

  • decimal.js:

    decimal.js excels in handling decimal arithmetic with high precision. It supports various rounding modes and ensures that calculations remain accurate, making it ideal for financial applications where decimal representation is crucial.

Performance

  • bignumber.js:

    bignumber.js is designed for high performance, especially in scenarios involving large numbers and complex calculations. It balances precision and speed, making it a good choice for applications that require extensive numerical operations.

  • big.js:

    big.js is lightweight and optimized for performance, making it suitable for applications where speed is essential. It has a smaller footprint compared to other libraries, which can be beneficial in performance-sensitive scenarios.

  • mathjs:

    mathjs is more comprehensive and may be less performant than the others due to its extensive feature set. However, it is still efficient for most applications, especially those requiring a mix of precision and advanced mathematical capabilities.

  • decimal.js:

    decimal.js may have a slightly higher overhead due to its advanced features, but it provides excellent performance for decimal arithmetic. It is optimized for scenarios where precision is paramount, such as financial calculations.

Feature Set

  • bignumber.js:

    bignumber.js offers a rich set of features for arbitrary-precision arithmetic, including rounding, formatting, and conversion functions. It is suitable for applications that require a comprehensive arithmetic solution.

  • big.js:

    big.js focuses on basic arithmetic operations and provides a simple API for handling large numbers. It is straightforward and easy to use, but lacks advanced mathematical functions.

  • mathjs:

    mathjs is a full-featured mathematics library that includes arbitrary-precision arithmetic along with a wide range of mathematical functions, including algebra, calculus, and statistics. It is ideal for applications that require both precision and advanced mathematical capabilities.

  • decimal.js:

    decimal.js provides advanced decimal arithmetic features, including various rounding modes and precise control over decimal places. It is particularly useful for applications in finance and accounting.

Ease of Use

  • bignumber.js:

    bignumber.js has a user-friendly API that is easy to understand, making it accessible for developers who need to perform precise calculations without extensive setup.

  • big.js:

    big.js is known for its simplicity and ease of use, making it a great choice for developers who need basic arbitrary-precision arithmetic without a steep learning curve.

  • mathjs:

    mathjs has a steeper learning curve due to its extensive feature set, but it offers comprehensive documentation and examples, making it easier for developers to leverage its full potential.

  • decimal.js:

    decimal.js may require a bit more understanding of its features due to its advanced capabilities, but it provides clear documentation to help users navigate its functionalities.

Community and Support

  • bignumber.js:

    bignumber.js has a moderate community and is widely used in various applications, providing a good amount of resources and support for developers.

  • big.js:

    big.js has a smaller community compared to other libraries, but it is well-maintained and has sufficient documentation for basic use cases.

  • mathjs:

    mathjs has a large and active community, with extensive documentation, tutorials, and examples available. It is well-supported and frequently updated, making it a reliable choice for complex mathematical applications.

  • decimal.js:

    decimal.js has a dedicated user base, especially in financial sectors, and offers good documentation and community support for its advanced features.

How to Choose: bignumber.js vs big.js vs mathjs vs decimal.js

  • bignumber.js:

    Opt for bignumber.js if you need a comprehensive solution for arbitrary-precision arithmetic with a focus on performance and flexibility. It supports a wide range of mathematical operations and is suitable for applications requiring extensive calculations, such as financial applications.

  • big.js:

    Choose big.js for its simplicity and lightweight nature when you need basic arbitrary-precision arithmetic without additional features. It is ideal for straightforward applications where performance is key and complex mathematical operations are not required.

  • mathjs:

    Use mathjs when you need a full-featured mathematics library that includes arbitrary-precision arithmetic along with a wide array of mathematical functions. It is perfect for applications that require both numerical precision and advanced mathematical capabilities, such as algebra, calculus, and statistics.

  • decimal.js:

    Select decimal.js if your application requires advanced decimal arithmetic and features like rounding modes and precision control. It is particularly useful for financial applications where decimal representation is crucial, providing a robust set of features for precise calculations.

README for bignumber.js

bignumber.js

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

npm version npm downloads CI


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.

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):

npm install
npm run build
# or: node build.js

A dist directory will be created containing the following:

Module formatDistributableType declaration
ES module (ESM)bignumber.mjsbignumber.d.mts
CommonJS (CJS)bignumber.cjsbignumber.d.cts
Browser (global)bignumber.jsbignumber.d.ts

Load

Browser

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

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

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

ES module

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

or, minified from a CDN:

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

Node.js

npm install bignumber.js

CommonJS

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

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

ES module

import BigNumber from 'bignumber.js';

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

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

Deno

// @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,

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

An error will be thrown if an invalid value is passed to the constructor.

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();                       // "1.111222233334444555566e+21"
x.toFixed();                        // "1111222233334444555566"

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.

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

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.

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.

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.

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))    // 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.

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.

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.

y = new BigNumber('1234567.898765')
y.toFormat(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.

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

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.

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

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                                 // [ 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.

// 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

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:

npm run build
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.

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:

npm run typecheck

Minify

To minify using, for example, terser:

npm install -g terser

Minify the browser/global bundle:

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

Licence

The MIT Licence.

See LICENCE.