Solve JS rounding bug

Source: Internet
Author: User

Previously, I used the tofixed function provided by JS to perform rounding operations. However, I encountered problems in actual use.

For example

 

    1. VaRMoney = 0.00542;// 0.006;
    2. Alert (number (money). tofixed (2 ));
    3. // 0.00

 

We can see that the above results are incorrect. The following method uses the math. Round Function skillfully to completely solve the Accuracy Problem of a very small number.

VaRMoney = 0.00542;// 0.006;

Alert (number (money). tofixed (2 ));

FunctionRound2 (number, fractiondigits ){

With(Math ){

ReturnRound (Number * POW (10, fractiondigits)/POW (10, fractiondigits );

}

}

Alert (round2 (money, 2 ));// 0.01 

Round Method
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.

Description
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.