📜  math floor javascript (1)

📅  最后修改于: 2023-12-03 15:17:33.432000             🧑  作者: Mango

Math.floor() in JavaScript

Introduction

Math.floor() is a built-in method in JavaScript that returns the largest integer less than or equal to a given number. It is often used to convert a floating-point number into an integer, but can also be used for other purposes.

Syntax
Math.floor(x)

The Math.floor() method takes a single argument x, which is the number to round down to the nearest integer. If x is not a number, Math.floor() will return NaN.

Example
Math.floor(3.14159); // 3
Math.floor(-3.14159); // -4
Math.floor(42); // 42
Math.floor('hello'); // NaN

In the first example, Math.floor() rounds down 3.14159 to 3. In the second example, Math.floor() rounds down -3.14159 to -4. In the third example, Math.floor() returns the argument 42 unchanged. In the fourth example, Math.floor() returns NaN because 'hello' is not a number.

Usage

Math.floor() is commonly used in situations where a floating-point number needs to be converted to an integer. This can be useful when working with arrays or other data structures that require integer indices. For example:

letarr=[1.23, 2.34, 3.45];
for(leti=0; i<arr.length; i++){
    console.log(Math.floor(arr[i]));
}

This code iterates over the array [1.23, 2.34, 3.45] and logs the floor of each element (1, 2, and 3, respectively) to the console.

Conclusion

In summary, Math.floor() is a useful built-in method in JavaScript for rounding a number down to the nearest integer. It can be used for converting floating-point numbers to integers or for other purposes as needed.