Home >Web Front-end >JS Tutorial >Differences between Javascript Math ceil(), floor(), and round() functions_Basic knowledge

Differences between Javascript Math ceil(), floor(), and round() functions_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 18:32:511451browse

The following introduces several methods for rounding decimal values ​​to integers: Math.ceil(), Math.floor() and Math.round(). These three methods follow the following rounding rules respectively:
◎Math.ceil() performs rounding up, that is, it always rounds the value up to the nearest integer;
◎Math.floor() performs rounding down, that is, it always rounds the value down to the nearest integer;
◎Math.round() performs standard rounding, that is, it always rounds the value to the nearest integer (this is also the rounding rule we learned in math class).

Here are examples of using these methods:

alert(Math.ceil(25.9)); //26
alert(Math.ceil(25.5)); //26
alert(Math.ceil(25.1)); //26
alert(Math.round(25.9)); //26
alert(Math.round(25.5)); //26
alert(Math.round(25.1)); //25
alert(Math.floor(25.9)); //25
alert(Math.floor(25.5)); //25
alert(Math.floor(25.1)); //25

Nanchang Network Company technical staff summary: For all values ​​between 25 and 26 (excluding 26), Math.ceil() always returns 26 because it performs upward rounding. The Math.round() method only returns 26 when the value is greater than or equal to 25.5; otherwise it returns 25. Finally, Math.floor() returns 25 for all values ​​between 25 and 26 (excluding 26).

Here are some additions:
ceil(): Carry the decimal part to the integer part.
Such as:

Math.ceil(12.2)//Return 13
Math.ceil(12.7)//Return 13
Math.ceil(12.0)// returns 12

floor(): All values ​​are discarded and only integers are retained.
Such as:

Math.floor(12.2)// returns 12
Math.floor(12.7)//Return 12
Math.floor(12.0)//Return 12

round(): Rounding
Such as:

Math.round(12.2)// returns 12
Math.round(12.7)//Return 13
Math.round(12.0)//Return 12

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn