totn JavaScript

JavaScript: Math floor() function

This JavaScript tutorial explains how to use the math function called floor() with syntax and examples.

Description

In JavaScript, floor() is a function that is used to return the largest integer value that is less than or equal to a number. In other words, the floor() function rounds a number down and returns an integer value. Because the floor() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

Syntax

In JavaScript, the syntax for the floor() function is:

Math.floor(number);

Parameters or Arguments

number
The number used to find the largest integer value.

Returns

The floor() function returns the largest integer value that is less than or equal to a number.

Note

  • Math is a placeholder object that contains mathematical functions and constants of which floor() is one of these functions.

Example

Let's take a look at an example of how to use the floor() function in JavaScript.

For example:

console.log(Math.floor(32.65));
console.log(Math.floor(8.1));
console.log(Math.floor(-4.2));

In this example, we have invoked the floor() function using the Math class.

We have written the output of the floor() function to the web browser console log, for demonstration purposes, to show what the floor() function returns.

The following will be output to the web browser console log:

32
8
-5

In this example, the first output to the console log returned 32 which is 32.65 rounded down to an integer value.

The second output to the console log returned 8 which is 8.1 rounded down to an integer value.

The third output to the console log returned -5 which is -4.2 rounded down to an integer value. Notice that when dealing with negative numbers, the floor() function rounds away from zero and in this case, returned -5 and not -4.