JavaScript Math and Numbers
What are Numbers in JavaScript?
JavaScript uses a single Number type to represent all kinds of numeric values — including:
- Integers:
1
,42
,-5
- Floating-point numbers (decimals):
3.14
,-0.99
- Exponential numbers:
1.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.
Basic Arithmetic Operators
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 |
Increment and Decrement
let x = 5;
x++; // x = 6
x--; // x = 5
You can also use:
- x += 2
- x *= 3
- x /= 2, etc.
Working with the Math
Object
JavaScript provides a built-in Math
object with many methods and properties.
Common Math Methods
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 a Range
// Random number between 1 and 10
let random = Math.floor(Math.random() * 10) + 1;
console.log(random);
Number Conversion
parseInt()
- Converts string to integer
let n = parseInt("42"); // 42
parseFloat()
- Converts string to float
let n = parseFloat("3.14"); // 3.14
Number()
- Converts any type to number
Number("10") // 10
Number(true) // 1
Number("abc") // NaN
isNaN()
- Is Not a Number?
console.log(isNaN("abc")); // true
console.log(isNaN(123)); // false
Dealing with Decimals
Sometimes 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)
Number Methods
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" |
🧪 Practice Exercise:
Task:
- Write a program that adds, subtracts, multiplies and divides two numbers.
- Generate a random number between 1 and 100.
- Round
4.675
to 2 decimal places usingtoFixed()
. - Convert
"123.45"
to a number and multiply it by2
. - Get the square root of any number using
Math.sqrt()
.