JavaScript Math floor() method - JavaScript Tutorial

JavaScript Math floor() method

BLUF: This tutorial on JavaScript Math floor() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Math floor() method

Understanding JavaScript Math floor() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The JavaScript method math.floor reduces a specified number to the nearest lower integer and provides that value as the output. In cases where the input number is already an integer, the floor method will return it unchanged.

Syntax

The syntax for the floor method is illustrated as follows:

Example

Math.floor(num)

Parameter

num - A number.

Return

The greatest integer value that is less than or equal to the specified number.

JavaScript Math floor method example

In this section, we will explore the floor method by examining several examples.

Example 1

Let’s examine an example that reduces the specified number to the nearest integer value.

Example

<script>

document.writeln(Math.floor(7.2)+"<br>");

document.writeln(Math.floor(0.2));

</script>

Output:

Example 2

In this instance, we will demonstrate the utilization of the floor method with negative numerical values.

Example

<script>

document.writeln(Math.floor(-7.2)+ "<br>");

document.writeln(Math.floor(-0.2));

</script>

Output:

Output

-8

-1

Example 3

In this section, you have the opportunity to evaluate the floor method using your own custom test scenarios.

Example

<script>

function display()

{

  var x=document.getElementById("num").value;

document.getElementById("result").innerHTML=Math.floor(x);

}

</script>

<form>

  Enter a number: <input type="text" id="num">

  <input type="button"  onclick="display()" value="submit">

  </form>

  <p><span id="result"></span></p>

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience