When dealing with numbers, you might need to round them off. It is then the floor() method is used.
What does Math.floor do?
Usage of :
We need to use the dot(.) operator with the Math Class to use the floor method.
In the above syntax, ‘x’ is any given number passed as a parameter to be round off.
Note– If the number passed is an integer then, it has no effect.
JS Math.floor Examples
What is Math.floor(3.6)?
Let’s check for a positive decimal number 3.6.
let x = Math.floor(3.6); console.log(x); // 3
What about Math.floor(5.5) evaluates to?
let x = Math.floor(5.5); console.log(x); // 5
Again, for 5.5 if we use Math.floor to round it, we get 5 as the returned value.
What about negative numbers?
let a = Math.floor(-4.1); console.log(a); // 5 let b = Math.floor(-4.9); console.log(b); // 5 let c = Math.floor(-4.5); console.log(c); // 5
Finally, what if we pass an Integer?
let a = Math.floor(0); console.log(a); // 0 let b = Math.floor(7); console.log(b); // 7
As mentioned earlier, If we pass an integer as a parameter to the floor method, the value returns are the same.