JavaScript Numbers
JavaScript Numbers
Section titled “JavaScript Numbers”JavaScript has a single primary type for numbers. Numbers can be written with or without decimals.
Additionally, ES2020 introduced BigInt for integers of arbitrary precision.
JavaScript Number Type
Section titled “JavaScript Number Type”Standard JavaScript numbers can be integers or floating-point values:
const pi = 3.14; // A number with decimalsconst count = 100; // A number without decimalsExtremely large or small numbers can be written with scientific (exponent) notation:
const largeNumber = 1.23e7; // 12,300,000const smallNumber = 1.23e-4; // 0.000123Numbers are 64-bit Floating Point (IEEE 754)
Section titled “Numbers are 64-bit Floating Point (IEEE 754)”Unlike many other programming languages, JavaScript does not define different types of numbers for its primary number type (e.g., integers, short, long, float).
JavaScript numbers are always stored as double-precision floating-point numbers, following the international IEEE 754 standard. This format stores numbers in 64 bits:
| Fraction (Mantissa) | Exponent | Sign |
|---|---|---|
| 52 bits (0 - 51) | 11 bits (52 - 62) | 1 bit (63) |
Numeric Precision
Section titled “Numeric Precision”Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
const x = 999999999999999; // x will be 999999999999999const y = 9999999999999999; // y will be 10000000000000000 (loses precision)Floating-point arithmetic is not always 100% accurate due to the binary representation:
const z = 0.2 + 0.1; // z might be 0.30000000000000004To handle financial calculations or situations requiring high precision with decimals, consider using libraries designed for decimal arithmetic or scaling numbers (e.g., working with cents instead of dollars).
For very large integers beyond the safe integer limit (Number.MAX_SAFE_INTEGER), use BigInt.
Numeric Bases
Section titled “Numeric Bases”JavaScript supports several numeric bases:
- Decimal (base 10): Default (e.g.,
123). - Hexadecimal (base 16): Prefix with
0x(e.g.,const hex = 0xFF; // 255). - Binary (base 2): Prefix with
0b(ES6+) (e.g.,const bin = 0b1010; // 10). - Octal (base 8): Prefix with
0o(ES6+) (e.g.,const oct = 0o17; // 15).
Note: Legacy octal literals (a leading zero, like 07) are deprecated in strict mode and should be avoided. Use the 0o prefix for octal numbers. |
|---|
The toString() method can convert a number to a string in a specified base:
const myNumber = 128;console.log(myNumber.toString(16)); // "80" (hexadecimal)console.log(myNumber.toString(8)); // "200" (octal)console.log(myNumber.toString(2)); // "10000000" (binary)Infinity and -Infinity
Section titled “Infinity and -Infinity”Infinity is a special numeric value representing positive infinity. -Infinity represents negative infinity. These values result from operations like division by zero or calculations exceeding the largest representable number.
const positiveInf = 2 / 0; // Infinityconst negativeInf = -2 / 0; // -Infinityconsole.log(typeof Infinity); // "number"NaN - Not a Number
Section titled “NaN - Not a Number”NaN is a special numeric value representing an invalid or unrepresentable number. It often results from arithmetic operations on non-numeric values or undefined operations (e.g., 0/0).
const result1 = 100 / "Apple"; // NaNconst result2 = Math.sqrt(-1); // NaNTo check if a value is NaN, use Number.isNaN() (preferred) or the global isNaN().
Number.isNaN(value): Returnstrueonly ifvalueisNaN. It does not coerce the argument.isNaN(value): Coerces the argument to a number first.isNaN("hello")istrue.
const val = 100 / "Apple";console.log(Number.isNaN(val)); // trueconsole.log(isNaN(val)); // true
console.log(Number.isNaN("test")); // falseconsole.log(isNaN("test")); // true (because "test" coerces to NaN)Any arithmetic operation involving NaN results in NaN. typeof NaN is "number".
BigInt (ES2020)
Section titled “BigInt (ES2020)”BigInt is a newer numeric type in JavaScript that can represent integers with arbitrary precision. This is useful for numbers larger than Number.MAX_SAFE_INTEGER.
Create a BigInt by appending n to an integer literal or by calling the BigInt() function.
const veryLargeNumber = 9007199254740991n; // Max safe integerconst evenLarger = veryLargeNumber + 1n; // 9007199254740992nconst alsoLarge = BigInt("9007199254740993");
console.log(typeof evenLarger); // "bigint"Note: BigInts cannot be mixed with regular Numbers in arithmetic operations directly; explicit conversion is needed. They also don’t work with Math object methods.
Numbers as Objects (Avoid)
Section titled “Numbers as Objects (Avoid)”JavaScript numbers are normally primitive values. However, numbers can also be defined as objects using new Number().
const x = 123; // Primitive numberconst y = new Number(123); // Number object
console.log(typeof x); // "number"console.log(typeof y); // "object"Strongly avoid creating Number objects using new Number(). It slows down execution, leads to confusing behavior with equality checks (===), and offers no real benefits over primitive numbers. |
|---|
Number Properties and Methods
Section titled “Number Properties and Methods”Primitive numbers do not have properties or methods themselves. However, JavaScript provides a Number object wrapper that allows primitive numbers to access built-in properties and methods.
Static Properties (accessed on Number itself):
Number.MAX_VALUE: Largest positive representable number.Number.MIN_VALUE: Smallest positive representable number (closest to zero).Number.MAX_SAFE_INTEGER: Maximum safe integer (2^53 - 1).Number.MIN_SAFE_INTEGER: Minimum safe integer (-(2^53 - 1)).Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITYNumber.NaN
Instance Methods (called on a number variable or literal):
num.toString(base): Converts number to string (optional base).num.toFixed(digits): Formats to fixed number of decimal places.num.toPrecision(precision): Formats to specified length.num.toExponential(fractionDigits): Returns string in exponential notation.
Global functions for number conversion/checking:
parseInt(string, radix): Parses string to integer.parseFloat(string): Parses string to floating-point number.isFinite(value): Checks if value is a finite number.Number.isInteger(value): Checks if value is an integer.
const maxVal = Number.MAX_VALUE;console.log(maxVal);
const num = 123.456;console.log(num.toFixed(2)); // "123.46"console.log(num.toPrecision(4)); // "123.5"For a complete list and details, refer to the MDN Web Docs for the Number object.