The Math floor JavaScript method will take a number and round it DOWN to the nearest integer. This is done using the Math.floor() method.

var num = Math.floor(1.6);

The above code would round the number 1.6 DOWN to 1.

Some other examples of Math.floor() are below:

var num = Math.floor(1.6);
var num1 = Math.floor(.6);
var num2 = Math.floor(-1.6);
var num3 = Math.floor(100.6);
var num4 = Math.floor(30);

Which would result in the following:

1
0
-2
100
30

Math.floor() in action using jQuery

Below we will provide code to let the user input a number, and then use the Math.floor() method to round the number down. Here is our simple HTML setup:

Type a number you want to use the Math.floor() method on below:




Below is the JavaScript and jQuery code which take the user input using the jQuery click() or on() keypress methods, and use the Math.floor() method on that user input and update the results below using the jQuery text() method.

$('#userVal').on('keypress',function(e) {
  if(e.which == 13) {
    $("#results").text(Math.floor($("#userVal").val()));
  }
});
$("#submitNum").click(function(){
  $("#results").text(Math.floor($("#userVal").val()));
});

The final code and output for this example is below:

Code Output:

Type a number you want to use the Math.floor() method on below:


Full Code:

Type a number you want to use the Math.floor() method on below:





<script>

$('#userVal').on('keypress',function(e) {
  if(e.which == 13) {
    $("#results").text(Math.floor($("#userVal").val()));
  }
});
$("#submitNum").click(function(){
  $("#results").text(Math.floor($("#userVal").val()));
});

</script>

Hopefully this article has been useful in helping you understand the JavaScript Math.floor() method.

Categorized in:

JavaScript,

Last Update: May 3, 2024