JavaScript Math.floor()
Syntax & Examples
Math.floor() static-method
The Math.floor() method in JavaScript returns the largest integer less than or equal to a given number. It is a static method of Math, meaning it is always used as Math.floor() and not as a method of a Math object created (Math is not a constructor).
Syntax of Math.floor()
The syntax of Math.floor() static-method is:
Math.floor(x)
This floor() static-method of Math returns the largest integer less than or equal to x.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
x | required | A number for which to return the largest integer less than or equal to it. |
Return Type
Math.floor() returns value of type Number
.
✐ Examples
1 Using Math.floor() with a positive number
In this example, we use the Math.floor()
method to find the largest integer less than or equal to 4.7.
For example,
- We call
Math.floor()
with 4.7 as the argument. - The method returns the largest integer less than or equal to 4.7.
- We log the result to the console using
console.log()
.
JavaScript Program
console.log(Math.floor(4.7));
Output
4
2 Using Math.floor() with a negative number
In this example, we use the Math.floor()
method to find the largest integer less than or equal to -4.7.
For example,
- We call
Math.floor()
with -4.7 as the argument. - The method returns the largest integer less than or equal to -4.7.
- We log the result to the console using
console.log()
.
JavaScript Program
console.log(Math.floor(-4.7));
Output
-5
3 Using Math.floor() with an integer
In this example, we use the Math.floor()
method on an integer, which returns the integer itself.
For example,
- We call
Math.floor()
with 5 as the argument. - The method returns the largest integer less than or equal to 5.
- We log the result to the console using
console.log()
.
JavaScript Program
console.log(Math.floor(5));
Output
5
Summary
In this JavaScript tutorial, we learned about floor() static-method of Math: the syntax and few working examples with output and detailed explanation for each example.