JavaScript has a single number type for both integers and decimals. That simplicity hides one famous gotcha (floating-point rounding) and a few tools worth knowing — the Math object, number formatting, and dates, which trip up nearly every beginner.
Numbers
Number("42") // 42 (string → number)parseInt("42px", 10) // 42 (stops at non-digit; always pass the radix 10)parseFloat("3.14") // 3.14(255).toString(16) // "ff" (to hex)Number.isInteger(5) // trueNumber.isNaN(x) // safe NaN check(1234.567).toFixed(2) // "1234.57" (returns a string!)
The floating-point trap
Computers store decimals in binary, which can't represent some values exactly. This bites everyone once:
0.1 + 0.2 // 0.30000000000000004 😱0.1 + 0.2 === 0.3 // false// Fixes:(0.1 + 0.2).toFixed(2) // "0.30"Math.round((0.1 + 0.2) * 100) / 100 // 0.3// For money, work in integer paise/cents, not rupees/dollars.
The Math object
Math.round(4.6) // 5 Math.floor(4.9) // 4 Math.ceil(4.1) // 5Math.max(3, 9, 1) // 9 Math.min(3, 9, 1) // 1Math.abs(-7) // 7 Math.sqrt(144) // 12Math.random() // 0 ≤ x < 1// A random integer 1–6:Math.floor(Math.random() * 6) + 1
Formatting numbers
Intl.NumberFormat formats numbers for a locale — currency, thousands separators, percentages — correctly and without hand-rolled logic:
new Intl.NumberFormat("en-IN", {style: "currency", currency: "INR"}).format(650000) // "₹6,50,000.00" (Indian grouping!)new Intl.NumberFormat("en-IN").format(1234567) // "12,34,567"
Dates
const now = new Date();now.getFullYear() // 2026now.getMonth() // 0–11 (0 = January — a classic gotcha!)now.getDate() // day of monthconst d = new Date("2026-01-12"); // parse ISO format (safest)d.toISOString() // "2026-01-12T00:00:00.000Z"now.toLocaleDateString("en-IN") // "12/1/2026"
Practice
Write a function that formats a rupee amount with Intl.NumberFormat, and one that returns a random integer between two bounds. Then reproduce the 0.1 + 0.2 problem and fix it two different ways.
Key takeaways
- 01One number type covers ints and decimals; parse with Number/parseInt(…, 10)/parseFloat.
- 02Floating point can't represent some decimals exactly (0.1 + 0.2 !== 0.3) — store money as integer units.
- 03The Math object has round/floor/ceil, max/min, abs, sqrt, random.
- 04Intl.NumberFormat formats currency and numbers correctly per locale.
- 05Date months are 0-indexed; parse ISO strings and reach for date-fns for real date work.
