BigInteger.js: Arbitrary-Length Integers

1.6.52 · active · verified Sun Apr 19

BigInteger.js is a robust JavaScript library for performing arithmetic operations on integers of unlimited size, circumventing JavaScript's standard number precision limitations. The current stable version is 1.6.52. While releases are not on a fixed schedule, the project is actively maintained, with recent updates addressing various fixes and TypeScript definitions. A key differentiator and recent major change is its evolution into a polyfill for the native JavaScript `BigInt` feature (introduced to TC39 in 2018). If the execution environment supports native `BigInt`, this library will transparently wrap the native implementation, otherwise, it provides its own software-based arbitrary-length integer solution. This makes it a highly compatible choice for environments with varying `BigInt` support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `bigInt` values from numbers and strings, perform arithmetic operations like factorial calculation, and use pre-defined constants, highlighting its use in handling large integer arithmetic beyond standard JavaScript number limits.

import bigInt from 'big-integer';

function calculateFactorial(n: number): bigInt.BigInteger {
  let result = bigInt.one;
  for (let i = 2; i <= n; i++) {
    result = result.times(i);
  }
  return result;
}

// Calculate factorial of a moderately large number
const numberToFactorial = 50;
const factorialResult = calculateFactorial(numberToFactorial);
console.log(`Factorial of ${numberToFactorial} is: ${factorialResult.toString()}`);

// Demonstrating operations with large string inputs to avoid JS number precision limits
const largeA = bigInt('123456789012345678901234567890');
const largeB = bigInt('987654321098765432109876543210');
const sum = largeA.plus(largeB);
console.log(`Sum of two large numbers: ${sum.toString()}`);

// Accessing pre-stored constants
console.log(`Zero: ${bigInt.zero.toString()}`);
console.log(`One: ${bigInt.one.toString()}`);
console.log(`Minus One: ${bigInt.minusOne.toString()}`);

// Note: The actual type of `factorialResult` might be native `BigInt` or `BigInteger` object
// depending on environment support and library's polyfill behavior.

view raw JSON →