What is Javascript Math.floor()?
Introduction
In this article, we look at how the floor function under the math module is used, its limitations, and related topics.Table of Contents
- What is Javascript Math.floor?
- Code and its explanation
- Limitations and Caveats
- Other Related Concepts
What is Javascript Math.floor?
Before we take a look at where the floor function can be used, let’s first understand what it does.The math.floor() function is used to return the closest integer that’s smaller than or equal to the given number. Because the floor function is a static method under Math, the placeholder object Math needs to be used. And needless to say, only integers and floating values can be passed as parameters.
Similarly, the Javascript Math.ceil() function returns the closest integer that’s larger or equal to the given number.
Syntax of Javascript Math.floor function
Math.floor(x)
Here x is the parameter.
Code and its explanation:
//implementation of javascript Math.floor function
console.log(Math.floor(6.6));
// expected output: 6
console.log(Math.floor(5.9));
// expected output: 5
console.log(Math.floor(5));
// expected output: 5
Note: Math.floor returns the smaller integer irrespective of how close they are to the larger integer, Eg: Math.floor(5.9) return 5 and not 6
Limitations and caveats
- Since Math.floor always returns the lower integer it’s best to avoid using it when dealing with money. Round() would be a better choice here
- Math.floor returns 0 if null is passed as a parameter