liveBook · Manning

Number type

As explained in Math for Web Design

The number type is the JavaScript primitive type for numeric values, including integers and floating-point numbers.

JavaScript uses one number type for integers and floating-point values. That makes arithmetic convenient for element dimensions, animations, dates, financial data, and array loops, but precision can produce surprising results. section 2.0 section 2.9

Every number is stored as a 64-bit IEEE 754 floating-point value. Only integers from -9,007,199,254,740,991 through 9,007,199,254,740,991 are guaranteed to remain precise; check boundaries with Number.isSafeInteger(). section 2.2.1

Use the number type with these practical constraints:

  • Expect decimal imprecision because binary representation cannot exactly store every decimal; for example, 0.1 + 0.2 !== 0.3. section 2.9
  • Use parentheses to clarify precedence, strict equality (===) to avoid coercion, and BigInt for integers beyond the safe number range; do not mix number and BigInt values directly. section 2.8 section 2.9
  • Use Math.round(), Math.floor(), and Math.ceil() for rounding, toFixed() for formatted decimals, and Math.random() for pseudo-random values in [0, 1). section 2.9

Safe integer boundary

Number.MAX_SAFE_INTEGER + 1 and Number.MAX_SAFE_INTEGER + 2 both produce 9007199254740992. The values are representable, but JavaScript can no longer reliably distinguish nearby integers. section 2.2.1

Listing 2.1 Working with unsafe integers
console.log(`The maximum safe integer is ${Number.MAX_SAFE_INTEGER}`);
const unsafeNum1 = Number.MAX_SAFE_INTEGER + 1;
const unsafeNum2 = Number.MAX_SAFE_INTEGER + 2;
console.log(`The maximum safe integer plus 1 is ${unsafeNum1}`);
console.log(`The maximum safe integer plus 2 is ${unsafeNum2}`);

Run the listing to observe how adding one and adding two beyond the safe boundary produce the same displayed value. section 2.2.1

How Math for Web Design covers it

How deep it goes
Explains IEEE 754 storage, safe integer limits, decimal imprecision, coercion, rounding, randomness, and BigInt boundaries.
Examples
Uses unsafe-integer additions, approximate equality, carousel indexing, currency formatting, and random RGB color generation.
What it assumes
Assumes basic JavaScript expressions and values while establishing number representation, operators, precision, and numeric boundaries.
What you can do after
Diagnose/debug precision, coercion, rounding, unsafe-integer, and remainder problems in JavaScript calculations.
How it connects
Connects number values with arithmetic operators, comparison operators, the Number object, BigInt, Math methods, and type coercion.

Also explained in

Compare how 6 books explain number type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Math for Web Design. The section links point to the parts of the book it draws on.