Numbers, Math & BigInt

10 questions found

Why does 0.1 + 0.2 not equal 0.3 exactly in JavaScript?

Beginner
JavaScript numbers use the IEEE 754 double-precision floating-point format, which can't represent most decimal fractions exactly in binary — this is a property of floating-point math shared by nearly all programming languages, not a JavaScript-specific bug.
console.log(0.1 + 0.2);            // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);    // false
Real-world example Avoiding == comparisons on computed floating-point totals in a shopping cart or financial calculation.

Common follow-ups: How do you correctly compare two floating-point numbers for 'close enough' equality?

Types & Coercion

What does Number.isInteger() check, and how is it different from typeof?

Beginner
Number.isInteger(x) returns true only if x is a number with no fractional part (e.g. 5, but not 5.5 or '5'); typeof would just say 'number' for both integers and decimals, without distinguishing them.
Number.isInteger(5);    // true
Number.isInteger(5.5);  // false
Number.isInteger('5');  // false (not even a number)
Real-world example Validating that a quantity field entered by a user is a whole number, not a fraction.

Common follow-ups: What's the difference between Number.isInteger() and the global isFinite()?

Error Handling

What are some commonly used Math object methods?

Beginner
Math.round(), Math.floor(), and Math.ceil() handle rounding; Math.max()/Math.min() find extremes among arguments; Math.random() generates a pseudo-random float between 0 (inclusive) and 1 (exclusive); Math.abs() returns absolute value.
Math.round(4.5);   // 5
Math.floor(4.9);   // 4
Math.random();      // e.g. 0.5834...
Math.max(3, 7, 2);  // 7
Real-world example Generating a random integer within a specific range for a dice-roll or ID-suffix generator.

Common follow-ups: How do you generate a random integer between two specific values using Math.random()?

Arrays & Array Methods

What is Number.MAX_SAFE_INTEGER and what breaks beyond it?

Intermediate
It's 2^53 - 1 (9007199254740991), the largest integer JavaScript's double-precision Number type can represent without losing precision. Beyond it, integers can silently round to a nearby representable value, causing incorrect arithmetic and equality checks.
console.log(Number.MAX_SAFE_INTEGER);           // 9007199254740991
console.log(9007199254740992 === 9007199254740993); // true! precision lost
Real-world example A bug where large database IDs (like 64-bit Snowflake IDs) get silently corrupted when passed through JavaScript as regular numbers.

Common follow-ups: How does BigInt solve this precision problem?

ArrayBuffer TypedArrays & Binary Data

What is BigInt and how do you create one?

Intermediate
BigInt is a separate numeric type that can represent arbitrarily large integers exactly, with no upper precision limit like regular Numbers. Create one by appending 'n' to an integer literal or calling BigInt(value).
const big = 9007199254740993n;
const big2 = BigInt('9007199254740993');
console.log(big === big2); // true
Real-world example Precisely representing 64-bit database IDs, cryptographic values, or very large financial totals.

Common follow-ups: Can you mix BigInt and Number directly in arithmetic expressions?

ArrayBuffer TypedArrays & Binary Data

Why does 9007199254740993n + 1 throw a TypeError, but 9007199254740993n + 1n does not?

Intermediate
JavaScript deliberately disallows implicit mixing of BigInt and Number in arithmetic, because silently converting one to the other could quietly reintroduce precision loss (defeating the whole purpose of BigInt) — you must explicitly convert one side to match the other's type.
9007199254740993n + 1;   // TypeError: Cannot mix BigInt and other types
9007199254740993n + 1n;  // 9007199254740994n -- works, both are BigInt
Real-world example Catching a bug early where a regular number accidentally got combined with a BigInt ID without explicit conversion.

Common follow-ups: How do you safely convert a BigInt to a Number when precision loss is acceptable?

Types & Coercion

Why is Number.parseFloat('123abc') valid but Number('123abc') returns NaN?

Advanced
parseFloat() parses as much of the leading numeric-looking text as it can and stops at the first invalid character, ignoring the rest. The Number() constructor, by contrast, requires the ENTIRE string to be a valid numeric representation, returning NaN if any part fails to parse.
parseFloat('123abc');  // 123
Number('123abc');       // NaN
parseFloat('  42.5px'); // 42.5
Real-world example Extracting a numeric value from a CSS measurement string like '42.5px' using parseFloat().

Common follow-ups: Why does this difference make Number() generally safer for strict input validation?

Types & Coercion

How do you correctly compare two floating-point numbers for 'close enough' equality?

Advanced
Instead of strict equality, check whether the absolute difference between the two numbers is smaller than a small tolerance (epsilon) value, since floating-point rounding means direct equality checks on computed results are unreliable.
function nearlyEqual(a, b, epsilon = Number.EPSILON * 100) {
  return Math.abs(a - b) < epsilon;
}
nearlyEqual(0.1 + 0.2, 0.3); // true
Real-world example Comparing computed totals in a financial or scientific calculation where exact equality checks would fail unpredictably.

Common follow-ups: What is Number.EPSILON and what does it represent exactly?

Error Handling

Why is BigInt generally the wrong tool for representing monetary amounts with decimals, like $19.99?

Advanced
BigInt only represents whole integers — it has no concept of a decimal point. The common workaround is to store money as an integer count of the smallest currency unit (e.g. cents) rather than trying to represent fractional dollars directly, whether using BigInt or regular Numbers.
// Store cents as an integer instead of dollars as a float
const priceInCents = 1999; // represents $19.99
const total = priceInCents * quantity; // exact integer math, no float errors
Real-world example Avoiding floating-point rounding errors in an e-commerce checkout by doing all money math in integer cents.

Common follow-ups: What dedicated libraries exist for precise decimal arithmetic in JavaScript, like decimal.js?

Design Patterns in JavaScript

How do bitwise operators like >>>, &, and | behave differently on BigInt versus Number?

Advanced
Most bitwise operators work on BigInt the same way conceptually (treating it as an arbitrary-precision two's-complement integer), EXCEPT the unsigned right shift (>>>), which is explicitly NOT supported on BigInt at all, since BigInt has no fixed bit-width to define an 'unsigned' representation against.
5n & 3n;    // 1n -- works fine
5n | 2n;    // 7n -- works fine
// (-5n) >>> 1n; // TypeError: BigInts have no unsigned right shift
Real-world example Implementing custom arbitrary-precision bit-manipulation logic, like a big-integer hashing algorithm.

Common follow-ups: Why does regular Number bitwise math internally convert operands to 32-bit integers first?

Types & Coercion