big.js vs bignumber.js vs decimal.js vs decimal.js-light
Precision Arithmetic in JavaScript Financial Applications
big.jsbignumber.jsdecimal.jsdecimal.js-lightSimilar Packages:

Precision Arithmetic in JavaScript Financial Applications

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
big.js05,19458.9 kB8a year agoMIT
bignumber.js07,009500 kB82 months agoMIT
decimal.js07,249284 kB22a year agoMIT
decimal.js-light0411-66 years agoMIT

Precision Arithmetic Libraries: big.js vs bignumber.js vs decimal.js vs decimal.js-light

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.

🧮 Core Arithmetic: Initialization 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"

⚙️ Configuration: Precision and Rounding

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"

🚫 Error Handling and Edge Cases

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
}

🌐 Real-World Scenarios

Scenario 1: Simple Shopping Cart Total

You need to sum item prices and apply a tax rate. Precision is key, but features are minimal.

  • ✅ Best choice: big.js
  • Why? It is lightweight and handles basic addition and multiplication perfectly without extra bloat.
import 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

Scenario 2: Crypto Currency Exchange

You need to handle very small fractions (Satoshis) and large numbers, with flexible rounding.

  • ✅ Best choice: bignumber.js
  • Why? It handles a wide range of exponents and offers robust configuration for different coin precisions.
import BigNumber from 'bignumber.js';

const rate = new BigNumber('0.00004521');
const amount = new BigNumber('15000000');

const value = amount.times(rate).toFixed(8);

Scenario 3: Scientific Calculation Dashboard

You need decimal precision plus trigonometric functions (sin, cos) for data visualization.

  • ✅ Best choice: decimal.js
  • Why? It is the only one in this list that supports advanced math functions alongside decimal precision.
import Decimal from 'decimal.js';

const angle = new Decimal(45);
const result = Decimal.sin(angle.times(Math.PI / 180));

Scenario 4: Legacy Mobile App Update

You are updating an old app that already uses decimal.js-light and bundle size is tight.

  • ✅ Best choice: decimal.js-light
  • Why? Stick with it to avoid refactoring costs, but plan to migrate to big.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);

📌 Summary Table

Featurebig.jsbignumber.jsdecimal.jsdecimal.js-light
Primary FocusBasic Decimal MathFlexible Decimal MathFull Precision MathLightweight Decimal Math
Bundle SizeSmallestSmallLargestSmall
Advanced Math❌ No❌ No✅ Yes (sin, cos, etc.)❌ No
ConfigurationGlobalGlobal / InstanceGlobal / InstanceGlobal / Instance
Error HandlingThrows ErrorConfigurableThrows DecimalErrorThrows Error
MaintenanceStableActiveActiveLow Activity

💡 Final Recommendation

Think in terms of complexity and longevity:

  • Need basic currency math? → Use big.js. It is purpose-built for this and nothing else.
  • Need flexibility and broad adoption? → Use bignumber.js. It is the industry standard for a reason.
  • Need scientific functions? → Use decimal.js. It is the most powerful tool here.
  • Maintaining old code? → 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.

How to Choose: big.js vs bignumber.js vs decimal.js vs decimal.js-light

  • big.js:

    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.

  • bignumber.js:

    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.

  • decimal.js:

    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.

  • decimal.js-light:

    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.

README for big.js

big.js

A small, fast JavaScript library for arbitrary-precision decimal arithmetic.

npm version npm downloads CI

Features

  • Simple API
  • Faster, smaller and easier-to-use than JavaScript versions of Java's BigDecimal
  • Only 6 KB minified
  • Replicates the toExponential, toFixed and toPrecision methods of JavaScript Numbers
  • Stores values in an accessible decimal floating point format
  • Comprehensive documentation and test set
  • No dependencies
  • Uses ECMAScript 3 only, so works in all browsers

The little sister to bignumber.js and decimal.js. See here for some notes on the difference between them.

Install

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

Browsers

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>

Node.js

$ npm install big.js

CommonJS:

const Big = require('big.js');

ES module:

import Big from 'big.js';

Deno

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';

Use

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.

Minify

To minify using, for example, npm and terser

$ npm install -g terser
$ terser big.js -c -m -o big.min.js

Test

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.

TypeScript

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.

Licence

MIT

Contributors

Financial supporters

Thank you to all who have supported this project via Open Collective, particularly Coinbase.