Numbers in JavaScript
Unlike many other programming languages that have distinct integer and floating-point types (e.g., int, float, double), JavaScript traditionally has only one number type: Number.
The Number Type
In JavaScript, all numbers are implemented in double-precision 64-bit floating-point format (IEEE 754). This means that internally, JavaScript represents both integers and decimals using the same floating-point specification.
let age = 25; // Integer
let price = 99.99; // Floating point
Floating Point Precision Issues
Because JavaScript uses binary floating-point representations, some decimal fractions cannot be represented exactly. This leads to the infamous rounding error:
console.log(0.1 + 0.2);
// Output: 0.30000000000000004
How to fix it:
To do accurate calculations with decimals (like currency), you can scale the numbers to integers, perform the math, and scale back down. Alternatively, use .toFixed() for display purposes:
// For display (returns a string)
let total = 0.1 + 0.2;
console.log(total.toFixed(2)); // "0.30"
// For calculation (scaling)
let totalCents = (0.1 * 100) + (0.2 * 100);
let accurateTotal = totalCents / 100; // 0.3
Special Numeric Values
JavaScript provides several special numeric values that belong to the Number type.
-
Infinityand-Infinity: Returned when a number exceeds the maximum limit or when dividing by zero.console.log(1 / 0); // Infinity -
NaN(Not-a-Number): Represents an unrepresentable or undefined mathematical operation.console.log("apple" / 2); // NaN console.log(typeof NaN); // "number" (ironically)
Checking for NaN
Because NaN === NaN is surprisingly false, you must use special methods to check for it:
// Number.isNaN is preferred over the global isNaN
// because it doesn't coerce the type first.
Number.isNaN(NaN); // true
Number.isNaN("hello"); // false
// Global isNaN (coerces to number first)
isNaN("hello"); // true (because "hello" coerces to NaN)
Parsing Numbers
Converting strings to numbers is a common task. JavaScript provides several ways to do this:
Number(str): Converts a string to a number. ReturnsNaNif it fails.parseInt(str, radix): Parses an integer from a string. It reads until it hits a non-numeric character. Always provide the radix (usually 10 for decimal).parseFloat(str): Parses a floating-point number from a string.- Unary plus (
+): A shorthand forNumber().
parseInt("100px", 10); // 100
parseFloat("3.14rem"); // 3.14
Number("100px"); // NaN
+"42"; // 42
The Math Object
JavaScript provides a built-in Math object for complex mathematical operations and constants.
Math.round(4.6); // 5 (Rounds to nearest integer)
Math.floor(4.9); // 4 (Rounds down)
Math.ceil(4.1); // 5 (Rounds up)
Math.trunc(4.9); // 4 (Removes the decimal part entirely)
Math.max(10, 20, 5); // 20
Math.min(10, 20, 5); // 5
Math.pow(2, 3); // 8 (Equivalent to 2 ** 3)
Math.sqrt(16); // 4
// Random number between 0 (inclusive) and 1 (exclusive)
Math.random();
// Random integer between 1 and 10
const randomInt = Math.floor(Math.random() * 10) + 1;
BigInt
The Number type can only safely represent integers between -(2^53 - 1) and 2^53 - 1. This limit is accessible via Number.MAX_SAFE_INTEGER.
If you need to work with integers larger than this (e.g., cryptographic keys, large database IDs), you must use the BigInt type, introduced in ES2020.
You create a BigInt by appending n to the end of an integer literal or calling BigInt().
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
const hugeNumber = 9007199254740991n + 2n;
console.log(hugeNumber); // 9007199254740993n
// Note: You cannot mix BigInt and Number in operations directly
// console.log(10n + 5); // TypeError
Summary
- JavaScript uses a 64-bit floating point system for all numbers, leading to quirks with decimal math.
- Use
parseInt()andparseFloat()to extract numbers from strings. - Rely on the
Mathobject for rounding, maximums, and random generation. - Use
BigIntwhen working with exceedingly large integers that exceed the safe limit.