Skip to content
Plurafy

Number and BigInt

Working with numbers and big integers

Handle floating-point precision issues, work with very large numbers, and perform numerical operations safely.

JavaScript’s Number type has limitations. BigInt was introduced for arbitrary-precision integers.

// Number types
const integer = 42;
const float = 3.14;
const negative = -99;
const scientific = 1.5e-10;
// Special values
console.log(Infinity); // Positive infinity
console.log(-Infinity); // Negative infinity
console.log(NaN); // Not a Number
// Number methods
Number.isNaN(NaN); // true
Number.isNaN('NaN'); // false (different from isNaN)
Number.isFinite(100); // true
Number.isInteger(100); // true
Number.isInteger(100.5); // false
// Ranges
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
// Problem: Floating-point representation
console.log(0.1 + 0.2); // 0.30000000000000004 (not 0.3!)
console.log(0.1 + 0.2 === 0.3); // false
// Solution: Use epsilon for comparison
function numbersEqual(a, b, tolerance = 1e-10) {
return Math.abs(a - b) < tolerance;
}
console.log(numbersEqual(0.1 + 0.2, 0.3)); // true
// Alternative: Work with integers
const totalCents = Math.round(10 + 20); // Work in cents
const dollars = totalCents / 100;
// Decimal library for precision
const Decimal = require('decimal.js');
const result = new Decimal(0.1).add(new Decimal(0.2));
console.log(result.toString()); // '0.3'
// BigInt for large integers
const big = 9007199254740992n; // Suffix 'n'
const big2 = BigInt('9007199254740992');
// Operations
console.log(big + 1n); // 9007199254740993n
console.log(big * 2n); // 18014398509481984n
console.log(big / 2n); // 4503599627370496n
// Comparison with Number
console.log(9007199254740992 === Number(big)); // true
console.log(9007199254740993 === Number(BigInt(9007199254740993))); // false!
// Cannot mix BigInt and Number
// console.log(1n + 2); // TypeError
// Convert before mixing
console.log(Number(1n) + 2); // 3
console.log(1n + BigInt(2)); // 3n
// Cryptography
const publicKey = 340282366920938463463374607431768211456n;
// Large IDs
const userId = BigInt('18446744073709551616');
// Arbitrary precision math
function factorial(n) {
if (n <= 1n) return 1n;
return n * factorial(n - 1n);
}
console.log(factorial(20n)); // Can handle large factorials
// JSON serialization (careful!)
const obj = { id: 123456789n };
// console.log(JSON.stringify(obj)); // TypeError!
// Solution: Custom replacer
const json = JSON.stringify(obj, (key, value) => {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
});
console.log(json); // '{"id":"123456789"}'
// String to number
parseInt('42'); // 42
parseInt('3.14'); // 3 (drops decimal)
parseFloat('3.14'); // 3.14
Number('42'); // 42
+'42'; // 42
// With radix
parseInt('1010', 2); // 10 (binary)
parseInt('FF', 16); // 255 (hexadecimal)
// Error handling
parseInt('hello'); // NaN
Number('hello'); // NaN
// Better parsing
function safeParseInt(str, radix = 10) {
const num = parseInt(str, radix);
if (isNaN(num)) {
throw new Error(`Cannot parse "${str}" as integer`);
}
return num;
}
// To string with specific base
(255).toString(16); // 'ff'
(8).toString(2); // '1000'
// Number formatting
const num = 1234567.89;
num.toFixed(2); // '1234567.89'
num.toExponential(2); // '1.23e+6'
num.toPrecision(5); // '1.2346e+6'
// Internationalization
const usd = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(1234567.89);
console.log(usd); // '$1,234,567.89'
const de = new Intl.NumberFormat('de-DE', {
minimumFractionDigits: 2
}).format(1234567.89);
console.log(de); // '1.234.567,89'
// Rounding
Math.round(4.5); // 5
Math.floor(4.9); // 4
Math.ceil(4.1); // 5
Math.trunc(4.9); // 4
// Absolute value
Math.abs(-42); // 42
// Min/max with spread
Math.min(...[3, 1, 4, 1, 5]); // 1
Math.max(...[3, 1, 4, 1, 5]); // 5
// Power and roots
Math.pow(2, 3); // 8
Math.sqrt(16); // 4
Math.cbrt(27); // 3
// Random
Math.random(); // [0, 1)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}