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

codeTap to expand ⛶
1// Floating-point precision
2console.log(0.1 + 0.2); // 0.30000000000000004 😱
3console.log(0.1 + 0.2 === 0.3); // false!
4// Fix: use toFixed or multiply
5console.log((0.1 + 0.2).toFixed(1)); // "0.3" (returns string!)
6console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // true
7
8// Special values
9console.log(1 / 0); // Infinity
10console.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!)
13
14// Useful Number methods
15console.log(Number.isInteger(5.0)); // true
16console.log(Number.isFinite(1/0)); // false
17console.log(Number.parseInt("42px")); // 42
18console.log(Number.parseFloat("3.14em")); // 3.14
19
20// Math object
21console.log(Math.floor(4.9)); // 4
22console.log(Math.ceil(4.1)); // 5
23console.log(Math.round(4.5)); // 5
24console.log(Math.trunc(-4.9)); // -4
25console.log(Math.max(1, 5, 3)); // 5
26
27// 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:

  1. Write a function that rounds a number to N decimal places
  2. Generate a random hex color code (e.g., "#A3F2B1")
  3. Write a function that converts Celsius to Fahrenheit
  4. 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; use Number.EPSILON for comparisons

  • Using isNaN() instead of Number.isNaN() — global isNaN('hello') returns true because it coerces first

  • Forgetting 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 money

  • Not knowing NaN === NaN is false — use Number.isNaN() to check for NaN

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Numbers & Math Object. Login to unlock this feature.