JavaScript uses a single Number type to represent all kinds of numeric values — including:
1, 42, -53.14, -0.991.5e3 (equals 1500)let a = 10;
let b = 3.14;NOTE:JavaScript does not have different types for int and float like some other languages.
| Operator | Description | Example |
|---|---|---|
+ | Addition | 5 + 3 → 8 |
- | Subtraction | 5 - 2 → 3 |
* | Multiplication | 5 * 3 → 15 |
/ | Division | 15 / 3 → 5 |
% | Modulus (remainder) | 7 / 3 → 1 |
** | Exponentiation | 2**3 → 8 |
let x = 5;
x++; // x = 6
x--; // x = 5You can also use:
JavaScript provides a built-in Math object with many methods and properties.
| Method | Description | Example |
|---|---|---|
Math.round() | Rounds to nearest integer | Math.round(4.6) → 5 |
Math.floor() | Rounds down | Math.floor(4.9) → 4 |
Math.ceil() | Rounds up | Math.ceil(4.1) → 5 |
Math.trunc() | Removes decimal part | Math.trunc(4.8) → 4 |
Math.abs() | Absolute value | Math.abs(-10) → 10 |
Math.pow() | Exponentiation | Math.pow(2, 3) → 8 |
Math.sqrt() | Square root | Math.sqrt(16) → 4 |
Math.max() | Highest value | Math.max(1, 5, 3) → 5 |
Math.min() | Lowest value | Math.min(1, 5, 3) → 1 |
Math.random() | Random number between 0 and 1 | Math.random() |
// Random number between 1 and 10
let random = Math.floor(Math.random() * 10) + 1;
console.log(random);let n = parseInt("42"); // 42let n = parseFloat("3.14"); // 3.14Number("10") // 10
Number(true) // 1
Number("abc") // NaNconsole.log(isNaN("abc")); // true
console.log(isNaN(123)); // falseSometimes floating-point math can be imprecise:
console.log(0.1 + 0.2); // 0.30000000000000004 😕You can fix it using toFixed():
let total = (0.1 + 0.2).toFixed(2); // "0.30" (as a string)| Method | Description | Example |
|---|---|---|
toFixed(n) | Rounds to n decimal places | (3.14159).toFixed(2) → "3.14" |
toString() | Converts number to string | (100).toString() → "100" |
typeof | Checks if it's a number | typeof 42 → "number" |
4.675 to 2 decimal places using toFixed()."123.45" to a number and multiply it by 2.Math.sqrt().