Number and BigInt
Working with numbers and big integers
Challenge
Section titled “Challenge”Handle floating-point precision issues, work with very large numbers, and perform numerical operations safely.
Explanation
Section titled “Explanation”JavaScript’s Number type has limitations. BigInt was introduced for arbitrary-precision integers.
Number Basics
Section titled “Number Basics”// Number typesconst integer = 42;const float = 3.14;const negative = -99;const scientific = 1.5e-10;
// Special valuesconsole.log(Infinity); // Positive infinityconsole.log(-Infinity); // Negative infinityconsole.log(NaN); // Not a Number
// Number methodsNumber.isNaN(NaN); // trueNumber.isNaN('NaN'); // false (different from isNaN)Number.isFinite(100); // trueNumber.isInteger(100); // trueNumber.isInteger(100.5); // false
// Rangesconsole.log(Number.MAX_VALUE); // 1.7976931348623157e+308console.log(Number.MIN_VALUE); // 5e-324console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991Floating-Point Precision
Section titled “Floating-Point Precision”// Problem: Floating-point representationconsole.log(0.1 + 0.2); // 0.30000000000000004 (not 0.3!)console.log(0.1 + 0.2 === 0.3); // false
// Solution: Use epsilon for comparisonfunction 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 integersconst totalCents = Math.round(10 + 20); // Work in centsconst dollars = totalCents / 100;
// Decimal library for precisionconst Decimal = require('decimal.js');const result = new Decimal(0.1).add(new Decimal(0.2));console.log(result.toString()); // '0.3'BigInt
Section titled “BigInt”// BigInt for large integersconst big = 9007199254740992n; // Suffix 'n'const big2 = BigInt('9007199254740992');
// Operationsconsole.log(big + 1n); // 9007199254740993nconsole.log(big * 2n); // 18014398509481984nconsole.log(big / 2n); // 4503599627370496n
// Comparison with Numberconsole.log(9007199254740992 === Number(big)); // trueconsole.log(9007199254740993 === Number(BigInt(9007199254740993))); // false!
// Cannot mix BigInt and Number// console.log(1n + 2); // TypeError
// Convert before mixingconsole.log(Number(1n) + 2); // 3console.log(1n + BigInt(2)); // 3nBigInt Applications
Section titled “BigInt Applications”// Cryptographyconst publicKey = 340282366920938463463374607431768211456n;
// Large IDsconst userId = BigInt('18446744073709551616');
// Arbitrary precision mathfunction 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 replacerconst json = JSON.stringify(obj, (key, value) => { if (typeof value === 'bigint') { return value.toString(); } return value;});console.log(json); // '{"id":"123456789"}'Parsing Numbers
Section titled “Parsing Numbers”// String to numberparseInt('42'); // 42parseInt('3.14'); // 3 (drops decimal)parseFloat('3.14'); // 3.14Number('42'); // 42+'42'; // 42
// With radixparseInt('1010', 2); // 10 (binary)parseInt('FF', 16); // 255 (hexadecimal)
// Error handlingparseInt('hello'); // NaNNumber('hello'); // NaN
// Better parsingfunction safeParseInt(str, radix = 10) { const num = parseInt(str, radix); if (isNaN(num)) { throw new Error(`Cannot parse "${str}" as integer`); } return num;}Formatting Numbers
Section titled “Formatting Numbers”// To string with specific base(255).toString(16); // 'ff'(8).toString(2); // '1000'
// Number formattingconst num = 1234567.89;num.toFixed(2); // '1234567.89'num.toExponential(2); // '1.23e+6'num.toPrecision(5); // '1.2346e+6'
// Internationalizationconst 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'Numeric Operations
Section titled “Numeric Operations”// RoundingMath.round(4.5); // 5Math.floor(4.9); // 4Math.ceil(4.1); // 5Math.trunc(4.9); // 4
// Absolute valueMath.abs(-42); // 42
// Min/max with spreadMath.min(...[3, 1, 4, 1, 5]); // 1Math.max(...[3, 1, 4, 1, 5]); // 5
// Power and rootsMath.pow(2, 3); // 8Math.sqrt(16); // 4Math.cbrt(27); // 3
// RandomMath.random(); // [0, 1)
function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min);}