Math.floor()
is a method in JavaScript that rounds down a given number to the nearest integer. In this response, I will explain how to use this method in JavaScript and provide code snippets to demonstrate its usage.
Basic Usage:
To use Math.floor()
, you need to provide a number as an argument to the function. The method will then return the largest integer less than or equal to the number.
Here’s an example of using Math.floor()
:
let num = 3.14159;
let roundedDownNum = Math.floor(num);
console.log(roundedDownNum); // Output: 3
In the example above, we create a variable num
and assign it a value of 3.14159
. We then call Math.floor()
with num
as the argument, which returns the largest integer less than or equal to num
. Finally, we assign the result of Math.floor(num)
to a new variable called roundedDownNum
, which will have a value of 3
. We then log the value of roundedDownNum
to the console, which will output 3
.
Examples:
Let’s explore some more examples of using Math.floor()
.
Example 1: Rounding Down a Positive Decimal Number:
let num = 5.6;
let roundedDownNum = Math.floor(num);
console.log(roundedDownNum); // Output: 5
In this example, we create a variable num
and assign it a value of 5.6
. We then call Math.floor()
with num
as the argument, which returns the largest integer less than or equal to num
. Finally, we assign the result of Math.floor(num)
to a new variable called roundedDownNum
, which will have a value of 5
. We then log the value of roundedDownNum
to the console, which will output 5
.
Example 2: Rounding Down a Negative Decimal Number:
let num = -5.6;
let roundedDownNum = Math.floor(num);
console.log(roundedDownNum); // Output: -6
In this example, we create a variable num
and assign it a value of -5.6
. We then call Math.floor()
with num
as the argument, which returns the largest integer less than or equal to num
. Finally, we assign the result of Math.floor(num)
to a new variable called roundedDownNum
, which will have a value of -6
. We then log the value of roundedDownNum
to the console, which will output -6
.
Example 3: Rounding Down a Number with Multiple Decimal Places:
let num = 2.71828;
let roundedDownNum = Math.floor(num);
console.log(roundedDownNum); // Output: 2
In this example, we create a variable num
and assign it a value of 2.71828
. We then call Math.floor()
with num
as the argument, which returns the largest integer less than or equal to num
.
Finally, we assign the result of Math.floor(num)
to a new variable called roundedDownNum
, which will have a value of 2
. We then log the value of roundedDownNum
to the console, which will output 2
.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.