🌱BeginnerJavaScript Fundamentals
Numbers & the Math Object
parseInt, parseFloat, toFixed, Number methods, and the Math object for common calculations.
Overview
JavaScript has a single `number` type (IEEE 754 double-precision float) that handles both integers and decimals. This simplicity has trade-offs: floating-point arithmetic can produce surprising results like `0.1 + 0.2 === 0.30000000000000004`.
The global `Number` function and its static methods help you convert values safely: `Number("42")` converts a string to a number; `Number.isNaN()` correctly checks for NaN; `Number.isFinite()` guards against Infinity. The `.toFixed(n)` method on a number rounds and formats to n decimal places as a string.
The built-in `Math` object provides mathematical constants and functions without needing any import. `Math.random()` generates random decimals; combine it with `Math.floor()` for random integers. `Math.max()` and `Math.min()` work on argument lists spread an array to use them on array data.
Key Points
- •`Number("42")` → 42; `Number("")` → 0; `Number("abc")` → NaN; `Number(null)` → 0
- •`parseInt("42px")` parse integer from string prefix; `parseFloat("3.14kg")` for decimals
- •`Number.isNaN(val)` safe NaN check (unlike global `isNaN` which coerces first)
- •`Number.isFinite(val)` returns false for Infinity, -Infinity, and NaN
- •`num.toFixed(2)` returns string with 2 decimal places: `(3.14159).toFixed(2)` → `"3.14"`
- •`Math.round()` nearest integer; `Math.ceil()` round up; `Math.floor()` round down
- •`Math.abs(n)` absolute value; `Math.max(a,b,...)` / `Math.min()` largest/smallest
- •`Math.random()` random float [0, 1); `Math.floor(Math.random() * n)` random int [0, n)
- •`Math.sqrt(n)` square root; `Math.pow(base, exp)` same as `base ** exp`
Examples
Number conversion and checking
// Converting to number
console.log(Number("42")); // 42
console.log(Number("3.14")); // 3.14
console.log(Number("")); // 0
console.log(Number("abc")); // NaN
console.log(Number(true)); // 1
console.log(Number(null)); // 0
// parseInt and parseFloat
console.log(parseInt("42px")); // 42 (stops at non-digit)
console.log(parseFloat("3.14s")); // 3.14
console.log(parseInt("0xFF", 16));// 255 (base 16)
// Safe NaN check
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("hello")); // false (no coercion)
console.log(Number.isFinite(1 / 0)); // false (Infinity)
console.log(Number.isFinite(42)); // trueFormatting numbers
const price = 9.99563;
// toFixed rounds and returns a string
console.log(price.toFixed(2)); // "10.00"
console.log(price.toFixed(0)); // "10"
// Format as currency
const amount = 1234.5;
console.log(`$${amount.toFixed(2)}`); // "$1234.50"
// toLocaleString for locale-aware formatting
const big = 1234567.89;
console.log(big.toLocaleString("en-US")); // "1,234,567.89"
// Number limits
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991Math object rounding and random
// Rounding variants
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.ceil(4.1)); // 5 (always up)
console.log(Math.floor(4.9)); // 4 (always down)
console.log(Math.trunc(4.9)); // 4 (truncate, not round)
console.log(Math.trunc(-4.9)); // -4 (floor would be -5)
// Random integer between min (inclusive) and max (exclusive)
function randInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
console.log(randInt(1, 7)); // random die roll 1–6
// Max/min with spread
const scores = [88, 95, 72, 91, 67];
console.log(Math.max(...scores)); // 95
console.log(Math.min(...scores)); // 67Common Mistakes
- `0.1 + 0.2 !== 0.3` floating-point precision issue; use `.toFixed()` or multiply to integers for money math
- Using global `isNaN("hello")` which returns `true` (coerces first) always use `Number.isNaN()`
- `parseInt` without a radix `parseInt("010")` may be parsed as octal in old environments; always pass 10: `parseInt("010", 10)`
Note
For currency calculations, always store values as integers (cents) and divide by 100 for display: ```const total = 1099; console.log((total / 100).toFixed(2)); // "10.99"``` This avoids floating-point rounding errors entirely.
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4