Javascript’s Math.floor() method takes a number as input and returns the largest integer less than or equal to the input number. Let us learn how it works by writing a simple Javascript program.
We will embed our Javascript code inside a HTML page like so:
In the above HTML page you see the basic elements of the page like the head element containing the title (“JavaScript’s Math floor() Method”) and a body with an empty script tag. The Javascript code goes inside these tags.
Here is some simple code to experiment with the Math.floor() method:
The output is:
As you can see 3.14 is truncated to 3.
Here are more examples:
The output is:
JavaScript’s Math.floor() Method applied to zero
Math.floor() applied to zero yields zero:
The output is:
JavaScript’s Math.floor() Method applied to negative numbers
Let us apply Math.floor() method to a negative number:
The output is:
Note that Math.floor() applied to -57.68 does not yield -57 (because that is greater than -57.68). The floor yields -58 because that is the largest integer smaller than -57.68 (picture the number line).
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.