Home  >  Article  >  Web Front-end  >  JavaScript Math.ceil method (round up the value)_Basic knowledge

JavaScript Math.ceil method (round up the value)_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:21:141711browse

JavaScript Math.ceil method
The Math.ceil method is used to round up a value, that is, to obtain the smallest integer greater than or equal to the value. The syntax is as follows:

Math.ceil(x)
Parameter description:

参数 说明
x 必需。必须是一个数值。

Tip: This method is the exact opposite of the Math.floor method.

Math.ceil method instance

<script language="JavaScript">
document.write( Math.ceil(0.35) + "<br />" );
document.write( Math.ceil(10) + "<br />" );
document.write( Math.ceil(-10) + "<br />" );
document.write( Math.ceil(-10.1) );
</script>

Run this example, output:

1
10
-10
-10

Math.ceil method error?
Try running the following example:

c213752d78643de9c16ab108c0325b4f document.write( Math.ceil(2.1/0.7) ); 2cacc6d41bbb37262a98f745aa00fbf0 The result of this example is not as expected. 3 (2.1/0.7= 3), but 4. This is obviously contrary to our common sense. Is it an error in the Math.ceil method?

The real situation is that when calculating 2.1/0.7, it is processed as floating point numbers. Due to the binary system, computers cannot be completely accurate with floating point numbers (that is, they usually lose a little progress), so the calculation result of 2.1/0.7 is not exactly equal to 3, but a little more than 3 (approximately: 3.00000000000000044409) . So after Math.ceil() is applied to this expression, the result is 4 .

Regarding the issue of inaccurate ceil function, it was also mentioned in the article "Solution to Inaccurate PHP Floating Point Calculation Comparison and Rounding". Round() can be conveniently used in PHP function to process. However, Math.round() in JavaScript is too rough, so a separate function must be written to handle this situation, that is, remove all excess values ​​after 1 decimal point, and then use the Math.ceil() method.

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