JavaScript Math.ceil method
The Math.ceil method is used to round up the numerical value, that is, to obtain the smallest integer greater than or equal to the numerical value. The syntax is as follows:
Math.ceil(x)
Parameter description:
| parameter | illustrate |
|---|---|
| x | Required. Must be a numeric value. |
Tip: This method is exactly the opposite of the Math.floor method.
Math.ceil method example
<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 and output:
1
10
-10
-10
Error in the Math.ceil method?
Try running the following example:
<script language="JavaScript"> document.write( Math.ceil(2.1/0.7) ); </script> The result of running this example is not to get 3 as we expected (2.1/0.7=3), but 4. This is obviously contrary to our common sense. Is it a mistake in the Math.ceil method?
The real situation is that when performing 2.1/0.7 calculations, they are processed according to floating point numbers. Due to binary relationships, it is impossible for computers to be completely accurate for 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 exceeds 3 a little (approximately: 3.00000000000000044409). So after the expression is applied to Math.ceil(), the result is 4.
Regarding the problem of inaccurate ceil function, it was also mentioned in the article "Solutions for Comparison and Inaccurate Rounding of PHP Floating Point Numbers Comparison and Rounding Inaccurate Solutions" that in PHP, the round() function can be easily processed. However, Math.round() in JavaScript is too rough, so a function must be written separately to deal with this kind of situation, that is, all the excess values after 1 decimal point are removed, and the Math.ceil() method is used.