JavaScript Math.floor() Method



The Math.floor() method in JavaScript accepts a numeric value as an argument, rounds down and returns the largest integer less than or equal to the provided number. For instance, if we provide "5.6" as an argument to this method, it returns "5" as a result. It method works same as "-Math.ceil(-x)".

This method is used when we need to convert a floating-point number to an integer but want to ensure the result is always rounded towards negative infinity.

Syntax

Following is the syntax of JavaScript Math.floor() method −

Math.floor(x);

Parameters

This method accepts only one parameter. The same is described below −

  • x: A numeric value.

Return value

This method returns the largest integer less than or equal to a given number (x). The result is a whole number with no decimal part.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript Math.floor() method −

<html>
<body>
<script>
   let number1 = Math.floor(-10.95);
   let number2 = Math.floor(-10.05);
   document.write(number1, "<br>", number2, "<br>");

   let number3 = Math.floor(10.05);
   let number4 = Math.floor(10.95);
   document.write(number3, "<br>", number4);
</script>
</body>
</html>

Output

As we can see in the output returned the largest integer less than or equal to the provided numbers.

Example 2

In this example, we are passing a numeric value as a string to this method −

<html>
<body>
<script>
   let number1 = Math.floor("-4.455");
   let number2 = Math.floor("4.455");
   document.write(number1, "<br>", number2);
</script>
</body>
</html>

Output

The floor() method converts the numeric string into a number and then rounds it DOWN to the nearest integer.

Example 3

The Math.floor() method works same as -Math.ceil(-x) method. Following is the example −

<html>
<body>
<script>
   const result = -Math.ceil(-5.6);
   document.write(result);
</script>
</body>
</html>

Output

If we execute the above program, it returns "5" as result.

Example 4

If we provide "null" as an argument to this method, it returns 0 as result −

<html>
<body>
<script>
   let number = Math.floor(null);
   document.write(number);
</script>
</body>
</html>

Output

If we execute the above program, it returns "0" as result.

Example 5

If we pass an empty number or non-numeric value as an argument to this method, it returns "NaN" as output −

<html>
<body>
<script>
   let number1 = Math.floor("Tutorialspoint");
   let number2 = Math.floor();

   document.write(number1, "<br>", number2);
</script>
</body>
</html>

Output

If we execute the above program, it returns "NaN" as result.

Example 6

If we provide NaN as an argument to this method, it returns "NaN" as output −

<html>
<body>
<script>
   let number = Math.floor(NaN);
   document.write(number);
</script>
</body>
</html>

Output

If we execute the above program, it returns "NaN" as result.

Advertisements