Categories
JavaScript Web development

JavaScript Math.floor() Method

JavaScript Math.floor() Method

The JavaScript Math.floor() method rounds a number (downwards) to the nearest integer and returns the result.

Syntax:

Math.floor(x)

Example1:

Click the button to round the number 2.7 downward to its nearest integer:

<!DOCTYPE html>
<html>
<body>

<button onclick="floorMethod()">Try it</button>
<p id="example-1"></p>

<script>
function floorMethod() {
  document.getElementById("example-1").innerHTML = Math.floor(2.7);
}
</script>

</body>
</html>

Output:


Example2:

Use the JavaScript Math.floor() method on different numbers:

<!DOCTYPE html>
<html>
<body>

<button onclick="floorMethod2()">Try it</button>
<p id="example-2"></p>

<script>
function floorMethod2() {
  var a = Math.floor(0.80);
  var b = Math.floor(0.95);
  var c = Math.floor(4.2);
  var d = Math.floor(6.1);
  var e = Math.floor(-8.9);
  var f = Math.floor(-3.3);

  var x = a + "," + b + "," + c + "," + d + "," + e + "," + f;
  document.getElementById("example-2").innerHTML = x;
}
</script>

</body>
</html>

Output:


Enjoy coding!