Skip to content

Math.floor() Function in Javascript, Uses, Limitations, Type Coercion

Math.floor() Function in Javascript, Uses, Limitations, Type Coercion


The Math.floor() function Rounds a number down to its closest integer, for example, Math.floor(5.99) returns 5.

What is Math.floor() in Javascript?

Math is a Javascript Built-in object with properties and methods for Mathematical function, constants.

The Math.floor() is one of the Static Methods in Javascript that takes a Number and rounds it down.

// 5

// 7

// 7

// -4

// -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

One of the known features of Javascript is the “Type Coercion”. Many people might think it is just a bad design, But in my opinion, if you know the type and also what a method is going to return, you should not be worried.

The type coercion happens when one type is converted into another. For example, a Number can turn into String.

// 27

// But Also
// 27

// And even
console.log(Math.floor("27.99" - 10));
// 17

So the 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?

Calculating gif


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!

// 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.