JavaScript's native number type uses IEEE 754 double-precision floating-point format, which leads to well-known precision errors (e.g., 0.1 + 0.2 !== 0.3). The packages big.js, bignumber.js, decimal.js, and decimal.js-light provide arbitrary-precision decimal arithmetic to solve this. They are essential for financial calculations, scientific data, and any domain where exact decimal representation is non-negotiable. While they share a common goal, they differ significantly in API design, feature completeness, mutability, and bundle impact.
When dealing with money, taxes, or scientific measurements in JavaScript, native floating-point math is a liability. The expression 0.1 + 0.2 resulting in 0.30000000000000004 is unacceptable in accounting. The big.js, bignumber.js, decimal.js, and decimal.js-light packages solve this by implementing arbitrary-precision decimal arithmetic. However, they are not interchangeable. Let's compare how they handle precision, configuration, and operations.
All four libraries allow you to create number instances that avoid floating-point errors, but their initialization and method chaining styles differ slightly.
big.js is minimal. It focuses strictly on decimal arithmetic. You create an instance and chain methods.
import Big from 'big.js';
const x = new Big('0.1');
const y = new Big('0.2');
// Operations return new Big instances
const sum = x.plus(y);
console.log(sum.toString()); // "0.3"
bignumber.js offers a similar API but is more forgiving with input types and supports more operations out of the box.
import BigNumber from 'bignumber.js';
const x = new BigNumber('0.1');
const y = new BigNumber('0.2');
// Supports method chaining and mixed types
const sum = x.plus(y);
console.log(sum.toString()); // "0.3"
decimal.js is immutable and rigorous. It handles a wider range of mathematical functions beyond basic arithmetic.
import Decimal from 'decimal.js';
const x = new Decimal('0.1');
const y = new Decimal('0.2');
// Immutable operations
const sum = x.plus(y);
console.log(sum.toString()); // "0.3"
decimal.js-light mirrors the decimal.js API but removes non-essential methods to reduce size.
import Decimal from 'decimal.js-light';
const x = new Decimal('0.1');
const y = new Decimal('0.2');
// Same API surface as decimal.js for basic math
const sum = x.plus(y);
console.log(sum.toString()); // "0.3"
Financial apps often require specific rounding rules (e.g., ROUND_HALF_UP for currency). Each library handles global or instance-level configuration differently.
big.js uses a global object Big to set precision and rounding mode. This affects all instances.
import Big from 'big.js';
// Set global precision and rounding mode
Big.DP = 2; // Decimal places
Big.RM = Big.roundHalfUp;
const result = new Big('1.555').plus('0.001');
console.log(result.toString()); // Respects global config
bignumber.js allows configuration via a static config method or per-instance cloning. It is more flexible.
import BigNumber from 'bignumber.js';
// Global configuration
BigNumber.config({ DECIMAL_PLACES: 2, ROUNDING_MODE: BigNumber.ROUND_HALF_UP });
const result = new BigNumber('1.555').plus('0.001');
console.log(result.toString()); // "1.56"
decimal.js uses a static set method for global config, but also allows passing configuration to the constructor for specific instances.
import Decimal from 'decimal.js';
// Global configuration
Decimal.set({ precision: 20, rounding: Decimal.ROUND_HALF_UP });
const result = new Decimal('1.555').plus('0.001');
console.log(result.toString()); // Respects config
decimal.js-light shares the configuration API of decimal.js but with fewer options available due to its stripped-down nature.
import Decimal from 'decimal.js-light';
// Configuration similar to decimal.js
Decimal.set({ rounding: Decimal.ROUND_HALF_UP });
const result = new Decimal('1.555').plus('0.001');
console.log(result.toString()); // "1.56"
How the libraries handle invalid inputs or division by zero can crash an app if not anticipated.
big.js throws standard JavaScript Error objects for invalid operations like division by zero or invalid strings.
import Big from 'big.js';
try {
const result = new Big('10').div(0);
} catch (e) {
console.error(e.message); // "Division by zero"
}
bignumber.js can be configured to throw errors or return special values like Infinity or NaN depending on settings.
import BigNumber from 'bignumber.js';
BigNumber.config({ ERRORS: true }); // Ensure errors are thrown
try {
const result = new BigNumber('10').div(0);
} catch (e) {
console.error(e.name); // "DivisionByZero"
}
decimal.js is strict. It throws DecimalError for invalid operations, making debugging easier.
import Decimal from 'decimal.js';
try {
const result = new Decimal('10').div(0);
} catch (e) {
console.error(e.name); // "DecimalError"
}
decimal.js-light behaves similarly to decimal.js regarding errors but may lack some of the deeper edge-case handling of the full version.
import Decimal from 'decimal.js-light';
try {
const result = new Decimal('10').div(0);
} catch (e) {
console.error(e.message); // Throws on division by zero
}
You need to sum item prices and apply a tax rate. Precision is key, but features are minimal.
big.jsimport Big from 'big.js';
const total = items.reduce((sum, item) => {
return sum.plus(new Big(item.price).times(item.quantity));
}, new Big(0));
const final = total.times(1.05); // Add 5% tax
You need to handle very small fractions (Satoshis) and large numbers, with flexible rounding.
bignumber.jsimport BigNumber from 'bignumber.js';
const rate = new BigNumber('0.00004521');
const amount = new BigNumber('15000000');
const value = amount.times(rate).toFixed(8);
You need decimal precision plus trigonometric functions (sin, cos) for data visualization.
decimal.jsimport Decimal from 'decimal.js';
const angle = new Decimal(45);
const result = Decimal.sin(angle.times(Math.PI / 180));
You are updating an old app that already uses decimal.js-light and bundle size is tight.
decimal.js-lightbig.js or bignumber.js in the long term.import Decimal from 'decimal.js-light';
// Existing logic remains unchanged
const val = new Decimal('100').div(3);
| Feature | big.js | bignumber.js | decimal.js | decimal.js-light |
|---|---|---|---|---|
| Primary Focus | Basic Decimal Math | Flexible Decimal Math | Full Precision Math | Lightweight Decimal Math |
| Bundle Size | Smallest | Small | Largest | Small |
| Advanced Math | ❌ No | ❌ No | ✅ Yes (sin, cos, etc.) | ❌ No |
| Configuration | Global | Global / Instance | Global / Instance | Global / Instance |
| Error Handling | Throws Error | Configurable | Throws DecimalError | Throws Error |
| Maintenance | Stable | Active | Active | Low Activity |
Think in terms of complexity and longevity:
big.js. It is purpose-built for this and nothing else.bignumber.js. It is the industry standard for a reason.decimal.js. It is the most powerful tool here.decimal.js-light is acceptable, but do not start new projects with it.Final Thought: Floating-point errors are silent bugs. Whichever library you choose, ensure you wrap all monetary values in it from the moment they enter your system until they leave. Do not mix native numbers with these instances.
Choose big.js if you need a small, fast library for basic decimal arithmetic without complex features like square roots or trigonometry. It is ideal for simple currency calculations in environments where bundle size is critical and you only need addition, subtraction, multiplication, division, and comparison.
Choose bignumber.js if you want a balance between feature set and ease of use. It offers a comprehensive API similar to big.js but includes support for non-integer exponents, square roots, and configurable precision. It is a safe default for most financial applications requiring robust error handling and flexibility.
Choose decimal.js if you require full-featured arbitrary-precision arithmetic, including complex operations like sine, cosine, and logarithms, alongside decimal math. It is immutable by default and handles edge cases rigorously. Best for scientific applications or complex financial systems where correctness outweighs bundle size.
Choose decimal.js-light only if you are maintaining a legacy codebase that depends on it. For new projects, prefer big.js or bignumber.js for lightweight needs or decimal.js for full features, as decimal.js-light is a stripped-down version that may lack long-term maintenance parity with the main decimal.js package.
A small, fast JavaScript library for arbitrary-precision decimal arithmetic.
toExponential, toFixed and toPrecision methods of JavaScript NumbersThe little sister to bignumber.js and decimal.js. See here for some notes on the difference between them.
The library is the single JavaScript file big.js or the ES module big.mjs.
Add Big to global scope:
<script src='path/to/big.js'></script>
ES module:
<script type='module'>
import Big from './path/to/big.mjs';
Get a minified version from a CDN:
<script src='https://cdn.jsdelivr.net/npm/[email protected]/big.min.js'></script>
$ npm install big.js
CommonJS:
const Big = require('big.js');
ES module:
import Big from 'big.js';
import Big from 'https://raw.githubusercontent.com/mikemcl/big.js/v7.0.1/big.mjs';
import Big from 'https://unpkg.com/big.js@latest/big.mjs';
In the code examples below, semicolons and toString calls are not shown.
The library exports a single constructor function, Big.
A Big number is created from a primitive number, string, or other Big number.
x = new Big(123.4567)
y = Big('123456.7e-3') // 'new' is optional
z = new Big(x)
x.eq(y) && x.eq(z) && y.eq(z) // true
In Big strict mode, creating a Big number from a primitive number is disallowed.
Big.strict = true
x = new Big(1) // TypeError: [big.js] Invalid number
y = new Big('1.0000000000000001')
y.toNumber() // Error: [big.js] Imprecise conversion
A Big number is immutable in the sense that it is not changed by its methods.
0.3 - 0.1 // 0.19999999999999998
x = new Big(0.3)
x.minus(0.1) // "0.2"
x // "0.3"
The methods that return a Big number can be chained.
x.div(y).plus(z).times(9).minus('1.234567801234567e+8').plus(976.54321).div('2598.11772')
x.sqrt().div(y).pow(3).gt(y.mod(z)) // true
Like JavaScript's Number type, there are toExponential, toFixed and toPrecision methods.
x = new Big(255.5)
x.toExponential(5) // "2.55500e+2"
x.toFixed(5) // "255.50000"
x.toPrecision(5) // "255.50"
The arithmetic methods always return the exact result except div, sqrt and pow
(with negative exponent), as these methods involve division.
The maximum number of decimal places and the rounding mode used to round the results of these methods is determined by the value of the DP and RM properties of the Big number constructor.
Big.DP = 10
Big.RM = Big.roundHalfUp
x = new Big(2);
y = new Big(3);
z = x.div(y) // "0.6666666667"
z.sqrt() // "0.8164965809"
z.pow(-3) // "3.3749999995"
z.times(z) // "0.44444444448888888889"
z.times(z).round(10) // "0.4444444445"
The value of a Big number is stored in a decimal floating point format in terms of a coefficient, exponent and sign.
x = new Big(-123.456);
x.c // [1,2,3,4,5,6] coefficient (i.e. significand)
x.e // 2 exponent
x.s // -1 sign
For advanced usage, multiple Big number constructors can be created, each with an independent configuration.
For further information see the API reference documentation.
To minify using, for example, npm and terser
$ npm install -g terser
$ terser big.js -c -m -o big.min.js
The test directory contains the test scripts for each Big number method.
The tests can be run with Node.js or a browser.
Run all the tests:
$ npm test
Test a single method:
$ node test/toFixed
For the browser, see runner.html and test.html in the test/browser directory.
big-vs-number.html is a old application that enables some of the methods of big.js to be compared with those of JavaScript's Number type.
The DefinitelyTyped project has a Typescript type definitions file for big.js.
$ npm install --save-dev @types/big.js
Any questions about the TypeScript type definitions file should be addressed to the DefinitelyTyped project.
Thank you to all who have supported this project via Open Collective, particularly Coinbase.