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 / 0
orparseInt("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 ton
decimal places
let num = 3.14159;
console.log(num.toFixed(2)); // "3.14"
toPrecision(n)
– Formats number ton
significant digitsparseInt(string)
– Converts string to integerparseFloat(string)
– Converts string to floating-pointisNaN(value)
– Checks if value isNaN
isFinite(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