Clean β’ Professional
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.
let integer = 42; // Integer
let float = 3.14; // Floating-point
let negative = -100; // Negative number
10, 53.14, 0.0012e3 = 2000, 1e-3 = 0.001Special Values:
Infinity β Represents a value larger than any number (1 / 0)Infinity β Negative infinity (1 / 0)NaN β "Not a Number" (0 / 0 or parseInt("abc"))Number.MAX_SAFE_INTEGER β 9007199254740991Number.MIN_SAFE_INTEGER β 9007199254740991+, , , /, % (modulus), * (exponentiation)let sum = 10 + 5; // 15
let power = 2 ** 3; // 8
++, -let x = 5;
x++; // x = 6
let result = "5" * 2; // 10
Number Methods:
toFixed(n) β Formats number to n decimal placeslet num = 3.14159;
console.log(num.toFixed(2)); // "3.14"
toPrecision(n) β Formats number to n significant digitsparseInt(string) β Converts string to integerparseFloat(string) β Converts string to floating-pointisNaN(value) β Checks if value is NaNisFinite(value) β Checks if value is a finite numberMath 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...
Number.MAX_SAFE_INTEGER, use BigIntlet bigNum = 123456789012345678901234567890n;
let anotherBigNum = BigInt("123456789012345678901234567890");
console.log(0.1 + 0.2); // 0.30000000000000004
console.log("5" + 3); // "53" (string concatenation)
typeof β Check if a value is a numberconsole.log(typeof 42); // "number"
console.log(typeof NaN); // "number"
Number.isInteger() β Check for integersconsole.log(Number.isInteger(42)); // true
console.log(Number.isInteger(3.14)); // falseΒ