JavaScript Math.ceil Method (Rounding values up) _ Basics

Source: Internet
Author: User
Tags numeric value

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.