Overview of Numbers
In JavaScript, numbers are a fundamental data type used to represent numeric values. JavaScript has a single Number type for both integers and floating-point numbers.
Number Type
- JavaScript numbers can be written with or without decimals:
let integer = 42; // Integer
let float = 3.14; // Floating-point
let negative = -100; // Negative number
Number Representation
- Integers: Whole numbers, e.g.,
10,5 - Floating-point: Numbers with decimals, e.g.,
3.14,0.001 - Scientific Notation: For very large or small numbers, e.g.,
2e3 = 2000,1e-3 = 0.001
Special Values:
Infinityβ Represents a value larger than any number (1 / 0)Infinityβ Negative infinity (1 / 0)NaNβ "Not a Number" (0 / 0orparseInt("abc"))
Number Limits
- JavaScript uses 64-bit floating-point representation (IEEE 754)
- Maximum safe integer:
Number.MAX_SAFE_INTEGERβ9007199254740991 - Minimum safe integer:
Number.MIN_SAFE_INTEGERβ9007199254740991 - Beyond these, precision may be lost
Common Operations
- Arithmetic:
+, , ,/,%(modulus),*(exponentiation)
let sum = 10 + 5; // 15
let power = 2 ** 3; // 8
- Increment / Decrement:
++,-
let x = 5;
x++; // x = 6
- Type Coercion: JS automatically converts strings to numbers in some operations
let result = "5" * 2; // 10
Built-in Methods
Number Methods:
toFixed(n)β Formats number tondecimal places
let num = 3.14159;
console.log(num.toFixed(2)); // "3.14"
toPrecision(n)β Formats number tonsignificant digitsparseInt(string)β Converts string to integerparseFloat(string)β Converts string to floating-pointisNaN(value)β Checks if value isNaNisFinite(value)β Checks if value is a finite number
Math Object Methods:
Math.round(num)β Round to nearest integerMath.floor(num)β Round downMath.ceil(num)β Round upMath.random()β Random number between 0 (inclusive) and 1 (exclusive)
console.log(Math.floor(3.7)); // 3
console.log(Math.random()); // e.g., 0.723...
BigInt
- For integers larger than
Number.MAX_SAFE_INTEGER, use BigInt
let bigNum = 123456789012345678901234567890n;
let anotherBigNum = BigInt("123456789012345678901234567890");
Common Pitfalls
- Floating-Point Precision:
console.log(0.1 + 0.2); // 0.30000000000000004
- Type Coercion:
console.log("5" + 3); // "53" (string concatenation)
Type Checking
typeofβ Check if a value is a number
console.log(typeof 42); // "number"
console.log(typeof NaN); // "number"
Number.isInteger()β Check for integers
console.log(Number.isInteger(42)); // true
console.log(Number.isInteger(3.14)); // falseΒ
