Math.floor() function Rounds a number down to its closest integer, for example,
Math.floor(5.99) returns 5.
Number and rounds it down.
console.log(Math.floor(5)); // 5 console.log(Math.floor(7.999)); // 7 console.log(Math.floor(7.009)); // 7 console.log(Math.floor(-3.95)); // -4 console.log(Math.floor(-3.05)); // -4
From the Example, you can see that
Math.floor() returns a
Number and it is always the largest integer less than or Equal to the provided number.
Math.floor() and Type Coercion
The type coercion happens when one type is converted into another. For example, a
Number can turn into
console.log(Math.floor(27.99)); // 27 // But Also console.log(Math.floor("27.99")); // 27 // And even console.log(Math.floor("27.99" - 10)); // 17
Math.floor() function expects a
Number as an argument but if you provide a number as
String type, it converts the string to an integer and returns an integer? whaaaa?
One of the caveats of the
Math.floor() function is passing
null as an argument.
You probably expect it to return
NaN (not a number), which is something that logically should be true but it returns 0 instead!
console.log(Math.floor(null)); // 0
There are other Static methods for
Math that might be useful to you based on your project requirements. I will be writing an article to cover different Methods and create a small ROI calculator shortly, so stay tuned.