# JavaScript math libraries

JavaScript math libraries add number types and operations that the built-in Number type cannot represent exactly. A decimal library stores each value as digits with a set precision rather than as a binary floating-point number. These libraries let payment systems, accounting tools, and scientific apps calculate prices, fractions, and large integers without rounding errors.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [decimal.js](#decimal-js) | 536.3M | 7.3K | Jul 2025 | MIT |
| [long.js](#long) | 502.9M | 920 | Apr 2025 | Apache-2.0 |
| [bignumber.js](#bignumber-js) | 345.6M | 7.0K | Jul 2026 | MIT |
| [BN.js](#bn-js) | 307.7M | 1.2K | Jul 2026 | MIT |
| [Fraction.js](#fraction-js) | 272.5M | 696 | Aug 2025 | MIT |
| [decimal.js-light](#decimal-js-light) | 246.7M | 411 | Sep 2020 | MIT |
| [big.js](#big-js) | 167.8M | 5.2K | Apr 2025 | MIT |
| [Math.js](#mathjs) | 21.3M | 15.1K | Apr 2026 | Apache-2.0 |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[decimal.js](#decimal-js) has the most monthly downloads in this comparison, at 522.7M.

## Capabilities

| Library | Global decimal precision | Exact rational type | Expression evaluation | Bitwise operations |
| --- | --- | --- | --- | --- |
| [decimal.js](#decimal-js) | Yes | No | No | No |
| [long.js](#long) | No | No | No | Yes |
| [bignumber.js](#bignumber-js) | Yes | No | No | No |
| [BN.js](#bn-js) | No | No | No | Yes |
| [Fraction.js](#fraction-js) | No | Yes | No | No |
| [decimal.js-light](#decimal-js-light) | Yes | No | No | No |
| [big.js](#big-js) | Yes | No | No | No |
| [Math.js](#mathjs) | Yes | Yes | Yes | Yes |

## Libraries

### decimal.js

[GitHub](https://github.com/MikeMcl/decimal.js) · [npm](https://www.npmjs.com/package/decimal.js) · [Docs](https://github.com/MikeMcl/decimal.js#readme)

Provides arbitrary-precision decimal arithmetic for JavaScript.

- Downloads / mo: 536.3M
- Stars: 7.3K
- Last release: 10.6.0
- License: MIT
- Capabilities: [From the decimal.js docs](https://github.com/MikeMcl/decimal.js#readme)

**Strengths**

- **Controls significant-digit precision.** Round arithmetic to a configured number of significant digits.
- **Provides decimal scientific functions.** Use trigonometry and non-integer powers with decimal values.

**Watch out for**

- **Number inputs can lose digits.** Pass long decimal values as strings to preserve their input digits.
- **Precision applies across arithmetic.** Account for rounding after operations beyond division.

```sh
npm install decimal.js
```

**josdejong/mathjs** (15.1K stars)

[josdejong/mathjs](https://github.com/josdejong/mathjs) 

```javascript
({ on, config }) => {
  const BigNumber = Decimal.clone({ precision: config.precision, modulo: Decimal.EUCLID })
  BigNumber.prototype = Object.create(BigNumber.prototype)

  /**
   * Attach type information
   */
  BigNumber.prototype.type = 'BigNumber'
  BigNumber.prototype.isBigNumber = true

  /**
   * Get a JSON representation of a BigNumber containing
   * type information
   * @returns {Object} Returns a JSON object structured as:
   *                   `{"mathjs": "BigNumber", "value": "0.2"}`
   */
  BigNumber.prototype.toJSON = function () {
    return {
      mathjs: 'BigNumber',
      value: this.toString()
    }
  }

  /**
   * Instantiate a BigNumber from a JSON object
   * @param {Object} json  a JSON object structured as:
   *                       `{"mathjs": "BigNumber", "value": "0.2"}`
   * @return {BigNumber}
   */
  BigNumber.fromJSON = function (json) {
    return new BigNumber(json.value)
  }

  if (on) {
    // listen for changed in the configuration, automatically apply changed precision
    on('config', function (curr, prev) {
      if (curr.precision !== prev.precision) {
        BigNumber.config({ precision: curr.precision })
      }
    })
  }

  return BigNumber
}
```

[src/type/bignumber/BigNumber.js](https://github.com/josdejong/mathjs/blob/a0c9f37a178e364caac81878ab87636ddbe1969d/src/type/bignumber/BigNumber.js#L7-L50) · [More projects using decimal.js →](https://dashboard.exa.ai/playground/search?q=JavaScript%20TypeScript%20projects%20using%20decimal.js%20for%20decimal%20arithmetic%2C%20configurable%20rounding%2C%20numeric%20conversion%20or%20mathematical%20expression%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import Decimal from 'decimal.js';
const value = new Decimal('0.1');
console.log(value.plus('0.2').toString());

```

From [README.md](https://mikemcl.github.io/decimal.js/)

### long.js

[GitHub](https://github.com/dcodeIO/long.js) · [npm](https://www.npmjs.com/package/long) · [Docs](https://github.com/dcodeIO/long.js#readme)

Represents a 64-bit two's-complement integer value as a Long class.

- Downloads / mo: 502.9M
- Stars: 920
- Last release: 5.3.2
- License: Apache-2.0
- Capabilities: [From the long.js docs](https://github.com/dcodeIO/long.js#readme)

```sh
npm install long
```

**Quickstart**

```javascript
import Long from 'long';
const value = Long.fromString('9007199254740993');
console.log(value.add(1).toString());

```

From [README.md](https://github.com/dcodeIO/long.js) · [Find projects using long.js →](https://dashboard.exa.ai/playground/search?q=long%20GitHub%20projects)

### bignumber.js

[GitHub](https://github.com/MikeMcl/bignumber.js) · [npm](https://www.npmjs.com/package/bignumber.js) · [Docs](https://github.com/MikeMcl/bignumber.js#readme)

Provides arbitrary-precision decimal and non-decimal numeric arithmetic.

- Downloads / mo: 345.6M
- Stars: 7.0K
- Last release: 11.1.5
- License: MIT
- Capabilities: [From the bignumber.js docs](https://github.com/MikeMcl/bignumber.js#readme)

**Strengths**

- **Handles multiple number bases.** Create values in decimal or another specified number base.
- **Preserves exact basic arithmetic.** Arithmetic outside division-related operations returns exact results.

**Watch out for**

- **Number inputs can lose digits.** Create high-precision values from strings instead of native numbers.
- **Division uses configured decimal places.** Set DECIMAL_PLACES and ROUNDING_MODE for division-related results.

```sh
npm install bignumber.js
```

**cardstack/cardstack** (326 stars)

[cardstack/cardstack](https://github.com/cardstack/cardstack) 

```javascript
export const convertAmountFromNativeValue = (
  value: BigNumberish,
  priceUnit: BigNumberish | null,
  decimals = 18
): string => {
  if (isNil(priceUnit) || isZero(priceUnit)) return '0';
  return new BigNumber(new BigNumber(value).dividedBy(priceUnit).toFixed(decimals, BigNumber.ROUND_DOWN)).toFixed();
};
```

[packages/cardpay-sdk/sdk/currency-utils/amount-conversion.ts](https://github.com/cardstack/cardstack/blob/dc2e0f9a42837feb073e3a3033b1a9188f50b4f7/packages/cardpay-sdk/sdk/currency-utils/amount-conversion.ts#L30-L37) · [More projects using bignumber.js →](https://dashboard.exa.ai/playground/search?q=JavaScript%20TypeScript%20projects%20using%20bignumber.js%20for%20decimal%20arithmetic%2C%20configurable%20rounding%2C%20numeric%20conversion%20or%20mathematical%20expression%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import BigNumber from 'bignumber.js';
const value = new BigNumber('0.1');
console.log(value.plus('0.2').toString());

```

From [README.md](https://mikemcl.github.io/bignumber.js/)

### BN.js

[GitHub](https://github.com/indutny/bn.js) · [npm](https://www.npmjs.com/package/bn.js)

Implements big number arithmetic in pure JavaScript.

- Downloads / mo: 307.7M
- Stars: 1.2K
- Last release: 5.2.5
- License: MIT
- Capabilities: [From the BN.js docs](https://github.com/indutny/bn.js)

```sh
npm install bn.js
```

**indutny/elliptic** (1.8K stars)

[indutny/elliptic](https://github.com/indutny/elliptic) 

```javascript
function toDER(enc) {
  var r = this.r.toArray();
  var s = this.s.toArray();

  // Pad values
  if (r[0] & 0x80)
    r = [ 0 ].concat(r);
  // Pad values
  if (s[0] & 0x80)
    s = [ 0 ].concat(s);

  r = rmPadding(r);
  s = rmPadding(s);

  while (!s[0] && !(s[1] & 0x80)) {
    s = s.slice(1);
  }
  var arr = [ 0x02 ];
  constructLength(arr, r.length);
  arr = arr.concat(r);
  arr.push(0x02);
  constructLength(arr, s.length);
  var backHalf = arr.concat(s);
  var res = [ 0x30 ];
  constructLength(res, backHalf.length);
  res = res.concat(backHalf);
  return utils.encode(res, enc);
}
```

[lib/elliptic/ec/signature.js](https://github.com/indutny/elliptic/blob/9b77436a59cc35eccf4ffb848259c8762a492ee7/lib/elliptic/ec/signature.js#L149-L176) · [More projects using BN.js →](https://dashboard.exa.ai/playground/search?q=bn.js%20GitHub%20projects)

**Quickstart**

```javascript
const BN = require('bn.js');
const a = new BN('dead', 16);
const b = new BN('beef', 16);
console.log(a.add(b).toString(16));

```

From [README.md](https://github.com/indutny/bn.js)

### Fraction.js

[GitHub](https://github.com/rawify/Fraction.js) · [npm](https://www.npmjs.com/package/fraction.js) · [Docs](https://raw.org/article/rational-numbers-in-javascript/)

Provides exact rational number arithmetic.

- Downloads / mo: 272.5M
- Stars: 696
- Last release: 5.3.4
- License: MIT
- Capabilities: [From the Fraction.js docs](https://raw.org/article/rational-numbers-in-javascript/)

```sh
npm install fraction.js
```

**norish-recipes/norish** (1.6K stars)

[norish-recipes/norish](https://github.com/norish-recipes/norish) 

```javascript
export function formatAmountAsFraction(n: number | null | string): string {
  if (n == null || n === "") return "";

  const num = typeof n === "string" ? parseFloat(n) : n;

  if (isNaN(num)) return String(n);
  if (Number.isInteger(num)) return String(num);

  try {
    // Use fraction.js with simplification to handle floating point imprecision
    // Tolerance of 0.01 allows 0.333 to become 1/3, 0.666 to become 2/3, etc.
    const frac = new Fraction(num).simplify(0.01);

    const wholePart = Math.floor(Math.abs(num));
    const isNegative = num < 0;

    // Get the fractional part
    const fracPart = frac.mod(1).abs();

    if (fracPart.valueOf() === 0) {
      // It's a whole number after simplification
      return String(Math.round(num));
    }

    const fractionStr = fracPart.toFraction();
    const unicodeFrac = toUnicodeFraction(fractionStr);

    // Check if we got a reasonable fraction (denominator <= 16)
    // If not, fall back to decimal
    const denominator = fracPart.d;

    if (denominator > 16) {
      return formatAmountAsDecimal(num);
    }

    const sign = isNegative ? "-" : "";

    if (wholePart === 0) {
      return `${sign}${unicodeFrac}`;
    }

    return `${sign}${wholePart} ${unicodeFrac}`;
  } catch {
    // If fraction.js fails, fall back to decimal
    return formatAmountAsDecimal(num);
  }
}
```

[packages/shared/src/lib/format-amount.ts](https://github.com/norish-recipes/norish/blob/2f47662130e16cc5ee7611e23846c39c564d41c3/packages/shared/src/lib/format-amount.ts) · [More projects using Fraction.js →](https://dashboard.exa.ai/playground/search?q=fraction.js%20GitHub%20projects)

**Quickstart**

```javascript
const Fraction = require('fraction.js');
const value = new Fraction(1, 3);
console.log(value.add(1, 6).toFraction());

```

From [README.md](https://github.com/rawify/Fraction.js)

### decimal.js-light

[GitHub](https://github.com/MikeMcl/decimal.js-light) · [npm](https://www.npmjs.com/package/decimal.js-light) · [Docs](https://github.com/MikeMcl/decimal.js-light#readme)

Provides an arbitrary-precision Decimal type for JavaScript.

- Downloads / mo: 246.7M
- Stars: 411
- Last release: 2.5.1
- License: MIT
- Capabilities: [From the decimal.js-light docs](https://github.com/MikeMcl/decimal.js-light#readme)

```sh
npm install decimal.js-light
```

**recharts/recharts** (27.7K stars)

[recharts/recharts](https://github.com/recharts/recharts) 

```javascript
function rangeStep(start: Decimal, end: Decimal, step: Decimal): Array<number> {
  let num = new Decimal(start);
  let i = 0;
  const result: Array<number> = [];

  // magic number to prevent infinite loop
  while (num.lt(end) && i < 100000) {
    result.push(num.toNumber());

    const next = num.add(step);
    /*
     * A non-positive step, or one too small to change `num` at Decimal's
     * current precision, leaves `num.lt(end)` true forever. Stop instead of
     * emitting 100000 identical values up to the iteration cap. This happens
     * with subnormal domains (the computed step collapses to zero) and with
     * very large values where adding a small step rounds back to the same
     * Decimal.
     */
    if (!next.gt(num)) {
      break;
    }
    num = next;
    i++;
  }

  return result;
}
```

[src/util/scale/util/arithmetic.ts](https://github.com/recharts/recharts/blob/070b2f790002e793a91c0fd1e480286c7e160c79/src/util/scale/util/arithmetic.ts#L38-L64) · [More projects using decimal.js-light →](https://dashboard.exa.ai/playground/search?q=decimal.js-light%20GitHub%20projects)

**Quickstart**

```javascript
import Decimal from 'decimal.js-light';
const value = new Decimal('2');
console.log(value.dividedBy('3').toString());

```

From [README.md](https://github.com/MikeMcl/decimal.js-light)

### big.js

[GitHub](https://github.com/MikeMcl/big.js) · [npm](https://www.npmjs.com/package/big.js) · [Docs](https://github.com/MikeMcl/big.js#readme)

Provides arbitrary-precision decimal arithmetic through a small numeric API.

- Downloads / mo: 167.8M
- Stars: 5.2K
- Last release: 7.0.1
- License: MIT
- Capabilities: [From the big.js docs](https://github.com/MikeMcl/big.js#readme)

**Strengths**

- **Preserves exact basic arithmetic.** Addition, subtraction, and multiplication return exact decimal results.
- **Offers strict numeric conversion.** Enable strict mode to reject imprecise conversions to native numbers.

**Watch out for**

- **Division still requires rounding.** Set DP and RM for division, square roots, and negative powers.

```sh
npm install big.js
```

**xxczaki/cashify** (408 stars)

[xxczaki/cashify](https://github.com/xxczaki/cashify) 

```javascript
export default function convert(
	amount: number | string,
	{ from, to, base, rates, BigJs }: Options,
): number {
	let numericAmount: number;
	let resolvedFrom = from;
	let resolvedTo = to;

	if (typeof amount === 'string') {
		const data = parse(amount);

		numericAmount = data.amount;
		resolvedFrom = data.from ?? from;
		resolvedTo = data.to ?? to;
	} else {
		numericAmount = amount;
	}

	if (Number.isNaN(numericAmount) || !Number.isFinite(numericAmount)) {
		throw new TypeError('The `amount` must be a finite number.');
	}

	if (BigJs) {
		return new BigJs(numericAmount)
			.times(getRate({ base, rates, from: resolvedFrom, to: resolvedTo }))
			.toNumber();
	}

	return (
		(numericAmount *
			100 *
			getRate({ base, rates, from: resolvedFrom, to: resolvedTo })) /
		100
	);
}
```

[src/convert.ts](https://github.com/xxczaki/cashify/blob/d4a4962ee945e82c1e134d0184b1c1bb393fe5c2/src/convert.ts#L5-L39) · [More projects using big.js →](https://dashboard.exa.ai/playground/search?q=JavaScript%20TypeScript%20projects%20using%20big.js%20for%20decimal%20arithmetic%2C%20configurable%20rounding%2C%20numeric%20conversion%20or%20mathematical%20expression%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import Big from 'big.js';
const value = new Big('0.1');
console.log(value.plus('0.2').toString());

```

From [README.md](https://mikemcl.github.io/big.js/)

### Math.js

[GitHub](https://github.com/josdejong/mathjs) · [npm](https://www.npmjs.com/package/mathjs) · [Docs](https://mathjs.org)

Provides a mathematics library for JavaScript and Node.js.

- Downloads / mo: 21.3M
- Stars: 15.1K
- Last release: 15.2.0
- License: Apache-2.0
- Capabilities: [From the Math.js docs](https://mathjs.org)

**Strengths**

- **Evaluates expressions with units.** Convert measurement units inside mathematical expressions.
- **Supports configurable decimal precision.** Configure BigNumber as the default numeric type for expression evaluation.

**Watch out for**

- **BigNumber support varies by function.** The random function does not support BigNumber values.
- **Heavy expressions need worker isolation.** Evaluate heavy expressions in a worker that can be terminated.

```sh
npm install mathjs
```

**javascriptdata/danfojs** (5.1K stars)

[javascriptdata/danfojs](https://github.com/javascriptdata/danfojs) 

```javascript
median(options?: { axis?: 0 | 1 }): Series {
        const { axis } = { axis: 1, ...options }

        if (this.$frameIsNotCompactibleForArithmeticOperation()) {
            throw Error("TypeError: median operation is not supported for string dtypes");
        }

        if ([0, 1].indexOf(axis) === -1) {
            throw Error("ParamError: Axis must be 0 or 1");
        }

        const newData = this.$getDataByAxisWithMissingValuesRemoved(axis)
        const resultArr = newData.map(arr => median(arr))
        if (axis === 0) {
            return new Series(resultArr, { index: this.columns });
        } else {
            return new Series(resultArr, { index: this.index });
        }

    }
```

[src/danfojs-base/core/frame.ts](https://github.com/javascriptdata/danfojs/blob/21d8c550b3aeba5f5ef0b46227a750307e203e70/src/danfojs-base/core/frame.ts#L859-L878) · [More projects using Math.js →](https://dashboard.exa.ai/playground/search?q=JavaScript%20TypeScript%20projects%20using%20mathjs%20for%20decimal%20arithmetic%2C%20configurable%20rounding%2C%20numeric%20conversion%20or%20mathematical%20expression%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import {create, all} from 'mathjs';
const math = create(all);
console.log(math.evaluate('sqrt(3^2 + 4^2)'));

```

From [README.md](https://mathjs.org/docs/core/configuration.html)

## FAQ

### Which JavaScript math library should I use?

[decimal.js](#decimal-js) suits decimal arithmetic with a configurable precision. [Fraction.js](#fraction-js) suits exact rational values. [Math.js](#mathjs) suits apps that evaluate math expressions with units, matrices, and complex numbers.

### How do I avoid floating-point precision errors in JavaScript?

A decimal library such as [decimal.js](#decimal-js) or [big.js](#big-js) stores values as decimal digits. Calculations then round only at the precision the code sets.

### What is Math.js?

[Math.js](#mathjs) is a math library for JavaScript and Node.js with an expression parser. It supports units, matrices, complex values, and several numeric types.

### Does JavaScript have a BigInt type?

JavaScript has a built-in BigInt type for integers of any size. [BN.js](#bn-js) and [long.js](#long) offer integer classes with their own APIs, including bitwise operations.

### decimal.js vs big.js: which should I use?

[decimal.js](#decimal-js) offers a larger API with significant-digit rounding. [big.js](#big-js) keeps a smaller decimal API with precision controls focused on division.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript math libraries mathjs decimal.js big.js bignumber.js examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
