JavaScript Math.floor()

Posted by

JavaScript Math.floor()

Introduction

The JavaScript Math.floor() method is a built-in JavaScript function that allows you to round a number down to the nearest integer. The JavaScript Math.floor() method returns the largest integer less than or equal to a given number.

Examples

To demonstrate the use of the JavaScript Math.floor() method, let’s look at some examples.

The following example rounds down the number 3.5 to 3:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

    var x = Math.floor(3.5);
    console.log(x); // Outputs: 3

[/dm_code_snippet]

The following example rounds down the number -3.5 to -4:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

    var x = Math.floor(-3.5);
    console.log(x); // Outputs: -4

[/dm_code_snippet]

The following example rounds down the number 4.2 to 4:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

    var x = Math.floor(4.2);
    console.log(x); // Outputs: 4

[/dm_code_snippet]

Syntax

The syntax for the Math.floor() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

    Math.floor(x);

[/dm_code_snippet]

The x parameter is the number you want to round down.

Browser Support

The Math.floor() method is supported in all major browsers.

Conclusion

The JavaScript Math.floor() method is a useful tool for rounding numbers down to the nearest integer. It is a simple and straightforward way to round numbers in JavaScript.