JavaScript Math
The Math object holds tools for common maths jobs. Each tool is a method called on Math itself.
Rounding three ways
round gives the nearest whole number. floor always goes down and ceil always goes up.
console.log(Math.round(4.5));
console.log(Math.round(4.4));
console.log(Math.floor(4.9));
console.log(Math.ceil(4.1));Largest and smallest
max returns the largest of its values. min returns the smallest.
console.log(Math.max(3, 9, 5));
console.log(Math.min(3, 9, 5));Roots and powers
sqrt returns the square root, the number that times itself gives the input. pow raises a number to a power.
console.log(Math.sqrt(16));
console.log(Math.pow(2, 3));Example
const roll = Math.floor(4.7);
const biggest = Math.max(12, 7, 20);
console.log(roll);
console.log(biggest);
console.log(Math.random() >= 0 && Math.random() < 1);Key points
- Math.round rounds to the nearest whole number.
- Math.floor rounds down and Math.ceil rounds up.
- Math.abs returns the size of a number without its sign.
- Random values differ on every run, so lessons never print one.
In this example, floor rounds 4.7 down to 4. max picks the largest of the three values. The last line checks that a random value sits in the allowed range, from 0 up to but not 1.
Note
Math methods are called on Math itself, like Math.round(4.5).
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does Math.floor(4.9) return?