Numbers & Math Object
📖 Concept
JavaScript has only one number type — IEEE 754 double-precision floating-point. This means all numbers (integers and decimals) are stored as 64-bit floats, which can cause precision issues.
The Math object provides mathematical constants and functions: Math.round(), Math.floor(), Math.ceil(), Math.random(), Math.max(), Math.min(), Math.abs(), Math.pow(), Math.sqrt(), Math.trunc().
Special numeric values: Infinity, -Infinity, NaN (Not a Number).
🏠 Real-world analogy: Floating-point precision is like trying to write 1/3 in decimal — you can get close (0.333...) but never exact. Similarly, 0.1 + 0.2 can't be stored exactly in binary.
💻 Code Example
1// Floating-point precision2console.log(0.1 + 0.2); // 0.30000000000000004 😱3console.log(0.1 + 0.2 === 0.3); // false!4// Fix: use toFixed or multiply5console.log((0.1 + 0.2).toFixed(1)); // "0.3" (returns string!)6console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // true78// Special values9console.log(1 / 0); // Infinity10console.log(typeof NaN); // "number" (ironic!)11console.log(NaN === NaN); // false (NaN is not equal to itself!)12console.log(Number.isNaN(NaN)); // true (use this instead!)1314// Useful Number methods15console.log(Number.isInteger(5.0)); // true16console.log(Number.isFinite(1/0)); // false17console.log(Number.parseInt("42px")); // 4218console.log(Number.parseFloat("3.14em")); // 3.141920// Math object21console.log(Math.floor(4.9)); // 422console.log(Math.ceil(4.1)); // 523console.log(Math.round(4.5)); // 524console.log(Math.trunc(-4.9)); // -425console.log(Math.max(1, 5, 3)); // 52627// Random number between min and max (inclusive)28function randomInt(min, max) {29 return Math.floor(Math.random() * (max - min + 1)) + min;30}31console.log(randomInt(1, 10)); // e.g., 7
🏋️ Practice Exercise
Mini Exercise:
- Write a function that rounds a number to N decimal places
- Generate a random hex color code (e.g., "#A3F2B1")
- Write a function that converts Celsius to Fahrenheit
- Check if a number is a perfect square using Math methods
⚠️ Common Mistakes
Trusting
0.1 + 0.2 === 0.3— floating-point arithmetic is imprecise; useNumber.EPSILONfor comparisonsUsing
isNaN()instead ofNumber.isNaN()— globalisNaN('hello')returnstruebecause it coerces firstForgetting that
parseInt('08')works in base 10 now, but always pass the radix:parseInt('08', 10)Using
Math.round()for currency — it rounds 2.5 to 3 but -2.5 to -2; use specific rounding logic for moneyNot knowing
NaN === NaNisfalse— useNumber.isNaN()to check for NaN
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Numbers & Math Object. Login to unlock this feature.