JavaScript Math.ceil method
The Math.ceil method is used to rounded up a number to get the smallest integer greater than or equal to the value. The syntax is as follows:
Math.ceil (x)
Parameter description:
Parameters |
Description |
X |
Necessary. Must be a numeric value. |
Tip: This method is just the opposite of the Math.floor method.
Math.ceil Method Instance
<script language= "JavaScript" >
document.write (Math.ceil (0.35) + "<br/>");
document.write (Math.ceil) + "<br/>");
document.write (Math.ceil ( -10) + "<br/>");
document.write (Math.ceil ( -10.1));
</script>
Run the example and output:
1
10
-10
-10
Error in Math.ceil method?
Try running the following example:
<script language= "JavaScript" > document.write (Math.ceil (2.1/0.7)); </script> The results of this example run are not as we expect to get 3 (2.1/0.7=3), but 4, which is obviously contrary to our common sense, is Math.ceil method error?
The real situation is that, in 2.1/0.7 calculations, it is handled in terms of floating-point numbers. The computer because of the binary relationship, it is not possible to complete the floating-point number of accurate (that is, usually lose a bit of progress), so the result of 2.1/0.7 calculation is not exactly equal to 3, but more than 31 points (about: 3.00000000000000044409). So the expression is applied to Math.ceil () and the result is 4.
About the problem of inaccurate ceil function, in the "PHP floating-point calculation comparison and the solution to the inaccurate method" also mentioned in the article, in PHP can be easily used in the round () function for processing. But Math.Round () in JavaScript is too rough, so you have to write a separate function to handle this kind of situation, taking away the extra value of the 1-bit decimal point, using the Math.ceil () method.