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.
In JavaScript, the syntax for the floor() function is:
Math.floor(x)
x
- The number used to find the largest integer value.The floor() function returns the largest integer value that is less than or equal to a number.
Note
console.log(Math.floor(32.65));
console.log(Math.floor(8.1));
console.log(Math.floor(-4.2));
Output
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.
The following example demonstrates the case no argument is passed.
console.log(Math.floor());
Output
NaN
The following example demonstrates the cases where 0 is returned.
var a = null;
var b = "";
var c = [];
console.log(Math.floor(a));
console.log(Math.floor(b));
console.log(Math.floor(c));
Output
0
0
0
The following example demonstrates the cases where NaN is returned and cases where it can be avoided.
var a = "JavaScript"; // non-numeric string
var b = [1, 2, 3, 4]; // array with more than one element
var c; // undefined variable
var d = {}; // empty object
console.log(Math.floor(a));
console.log(Math.floor(b));
console.log(Math.floor(c));
console.log(Math.floor(d));
var e = "23.5"; //numeric string
var f = [10.2]; //array with a single element
console.log(Math.floor(e));
console.log(Math.floor(f));
Output
NaN
NaN
NaN
NaN
23
10
The following example demonstrates that Math.ceil(x) returns same value as -Math.floor(-x).
var x = 45.6;
console.log(Math.ceil(x));
console.log(-Math.floor(-x));
Output
46
46
Thanks for reading !
#js #javascript