The Number Type β 64-bit Float
JavaScript uses the IEEE 754 double-precision 64-bit floating-point standard for all numbers. This means there is no separate int type β 42 and 42.0 are the same value.
// All of these are the same type
let integer = 42;
let float = 3.14;
let negative = -100;
let large = 1_000_000; // Numeric separators (ES2021) for readability
console.log(typeof integer); // "number"
console.log(typeof float); // "number"
console.log(42 === 42.0); // true β same value!
// Special numeric literals
console.log(0xFF); // 255 β hexadecimal
console.log(0b1010); // 10 β binary
console.log(0o17); // 15 β octal
Floating-Point Precision Issues
The most famous JavaScript number quirk: 0.1 + 0.2 is not exactly 0.3. This is not a JavaScript bug β it's a consequence of how IEEE 754 binary floating-point works in all programming languages.
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false!
// Solution 1: Use toFixed() for display (returns string)
console.log((0.1 + 0.2).toFixed(2)); // "0.30"
// Solution 2: Compare with an epsilon tolerance
const EPSILON = Number.EPSILON;
console.log(Math.abs(0.1 + 0.2 - 0.3) < EPSILON); // true
// Solution 3: Use integer math (work in cents, not dollars)
const price1 = 10; // 10 cents = $0.10
const price2 = 20; // 20 cents = $0.20
console.log((price1 + price2) / 100 + " dollars"); // "0.3 dollars"
When building financial applications, always represent monetary values as integers (e.g., cents) or use a dedicated decimal library. 0.1 + 0.2 = 0.30000000000000004 can cause real financial errors if you're not careful.
NaN, Infinity, and -Infinity
// NaN β Not a Number (but typeof NaN === "number"!)
console.log(parseInt("hello")); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(NaN === NaN); // false β NaN is not equal to itself
console.log(Number.isNaN(NaN)); // true β correct way to check
console.log(Number.isNaN("hello")); // false (unlike global isNaN!)
// Infinity
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Infinity + 1); // Infinity
console.log(Number.isFinite(42)); // true
console.log(Number.isFinite(Infinity)); // false
// Useful constants
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
Number Methods
const n = 123.456;
// toFixed β rounds to N decimal places (returns string)
console.log(n.toFixed(2)); // "123.46"
console.log(n.toFixed(0)); // "123"
// toString β converts to string, optional radix
console.log(n.toString()); // "123.456"
console.log((255).toString(16)); // "ff" (hexadecimal)
console.log((10).toString(2)); // "1010" (binary)
// Parsing strings to numbers
console.log(parseInt("42px")); // 42 (stops at non-numeric)
console.log(parseInt("3.9")); // 3 (truncates decimal)
console.log(parseFloat("3.14abc")); // 3.14
console.log(Number("42")); // 42
console.log(Number("42.5")); // 42.5
console.log(Number("42px")); // NaN β strict, no partial parsing
console.log(Number("")); // 0
// Number.isInteger
console.log(Number.isInteger(42)); // true
console.log(Number.isInteger(42.0)); // true (same value!)
console.log(Number.isInteger(42.5)); // false
The Math Object
The built-in Math object provides mathematical constants and functions. You don't create an instance β you use it directly as Math.method().
// Constants
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045
// Rounding
console.log(Math.round(4.5)); // 5 β rounds to nearest
console.log(Math.floor(4.9)); // 4 β rounds down (toward -Infinity)
console.log(Math.ceil(4.1)); // 5 β rounds up (toward +Infinity)
console.log(Math.trunc(4.9)); // 4 β removes decimal part
console.log(Math.trunc(-4.9)); // -4 (unlike floor which gives -5)
// Min, Max, Absolute value
console.log(Math.min(3, 1, 4, 1, 5, 9)); // 1
console.log(Math.max(3, 1, 4, 1, 5, 9)); // 9
console.log(Math.abs(-42)); // 42
// Power and roots
console.log(Math.pow(2, 10)); // 1024
console.log(Math.sqrt(144)); // 12
console.log(Math.cbrt(27)); // 3
// Random β returns float in [0, 1)
console.log(Math.random());
// Random integer between min (inclusive) and max (exclusive)
const randomInt = (min, max) => Math.floor(Math.random() * (max - min)) + min;
console.log(randomInt(1, 7)); // Random number 1β6 (like a die)
| Math Method | Description | Example |
|---|---|---|
Math.round(x) | Round to nearest integer | Math.round(4.5) β 5 |
Math.floor(x) | Round down | Math.floor(4.9) β 4 |
Math.ceil(x) | Round up | Math.ceil(4.1) β 5 |
Math.abs(x) | Absolute value | Math.abs(-5) β 5 |
Math.sqrt(x) | Square root | Math.sqrt(9) β 3 |
Math.pow(x, y) | x raised to power y | Math.pow(2, 8) β 256 |
Math.random() | Random float [0, 1) | Math.random() β 0.742... |
Math.log(x) | Natural logarithm | Math.log(Math.E) β 1 |
BigInt
BigInt handles integers larger than Number.MAX_SAFE_INTEGER (253β1). Create one by appending n to an integer literal.
const big = 9007199254740993n;
const huge = BigInt("123456789012345678901234567890");
console.log(big + 1n); // 9007199254740994n
console.log(typeof big); // "bigint"
// Cannot mix BigInt and Number directly
console.log(big + 1); // TypeError!
console.log(big + BigInt(1)); // OK: 9007199254740994n
Use Intl.NumberFormat to format numbers for display according to locale: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(1234.5) gives "$1,234.50". This handles locale-specific separators and currency symbols automatically.
ποΈ Practical Exercise
- Use
Math.random()to generate a random integer between 1 and 100 (inclusive). - Use
toFixed(2)to format0.1 + 0.2for display. - Compute the area of a circle with radius 7 using
Math.PI. Round the result to 2 decimal places. - Use
parseInt()andparseFloat()to extract numbers from"42px","3.14em", and"$9.99". - Format the number
1234567.89as a US dollar currency string usingIntl.NumberFormat.
π₯ Challenge Exercise
Write a function rollDice(sides, count) that simulates rolling count dice each with sides faces. Return an object containing: rolls (array of individual results), total (sum of all rolls), average (rounded to 1 decimal place), min, and max. Test it with rollDice(6, 5).
π Summary
- JavaScript uses one 64-bit float type for all numbers β no separate int type.
- Floating-point precision:
0.1 + 0.2 !== 0.3. UsetoFixed()for display or integer math for money. NaNis a number type; useNumber.isNaN()(not globalisNaN()) to check for it.parseInt()extracts leading integer;parseFloat()extracts leading float;Number()requires a valid number string.- The
Mathobject provides:round,floor,ceil,abs,sqrt,pow,random,min,max,PI,E. - Use
BigInt(appendn) for integers beyondNumber.MAX_SAFE_INTEGER.
Interview Questions
- Why does
0.1 + 0.2 !== 0.3in JavaScript? - What is the difference between
parseInt(),parseFloat(), andNumber()? - Why should you use
Number.isNaN()instead of the globalisNaN()? - What is
Number.MAX_SAFE_INTEGERand why does it matter? - How do you generate a random integer between two values in JavaScript?
Frequently Asked Questions
This is a JavaScript coercion quirk β an empty string is considered "empty" and coerces to 0 rather than NaN. The global isNaN("") also returns false for this reason. Always validate input before converting: check that the string is non-empty and matches a numeric pattern before calling Number().
For positive numbers they behave identically. For negative numbers: Math.floor(-4.7) gives -5 (rounds toward negative infinity), while Math.trunc(-4.7) gives -4 (simply removes the decimal, rounding toward zero). Use Math.floor() when you need consistent "round down" behavior.
Use: Math.floor(Math.random() * (max - min + 1)) + min. For example, to get a random number from 1 to 6 (inclusive): Math.floor(Math.random() * 6) + 1. The + 1 inside the range and the + min at the end are crucial for the bounds to be correct.
No. Math methods don't support BigInt β passing a BigInt to Math.sqrt() or similar will throw a TypeError. BigInt arithmetic uses regular operators (+, -, *, /, %, **) with all operands being BigInt. You must convert to Number first if you need Math operations.
Use Number.isInteger(n) β it returns true if the value is a number and has no fractional part. Note: Number.isInteger(42.0) returns true because 42.0 === 42 in JavaScript. Avoid n % 1 === 0 β it works but is less readable and semantic.