JS solves the problem of the accuracy of the numeric value rounded in by hour.

Source: Internet
Author: User

From: http://www.javaeye.com/topic/308966

 

Generally, we use the tofixed function provided by JS to perform rounding operations. However, when the value is very small, we find the problem.

For example:

  1. <Script language = "JavaScript">
  2. VaR money = 0.00542;
  3. Alert (number (money). tofixed (2 ));
  4. </SCRIPT>

The output result is 0.00, which is obviously incorrect.

The following method uses the math. Round Function to solve the hour-level precision problem.

For example:

  1. <Script language = "JavaScript">
  2. VaR money = 0.00542;
  3. // Alert (number (money). tofixed (2 ));
  4. Function round2 (number, fractiondigits ){
  5. With (math ){
  6. Return round (Number * POW (10, fractiondigits)/POW (10, fractiondigits );
  7. }
  8. }
  9. Alert (round2 (money, 2 ));
  10. </SCRIPT>

Output result: 0.01.

Note:

Round: returns the nearest integer to the given numeric expression.

Math. Round (number): the required number parameter is the value to be rounded to the nearest integer.

If the decimal part of number is greater than or equal to 0.5, the return value is the smallest integer greater than number. Otherwise, round returns the maximum integer less than or equal to number.

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.