A solution for the multiplication of JavaScript floating-point numbers with multiple decimal places _javascript tips

Source: Internet
Author: User

JavaScript in the multiplication of floating-point numbers, there will be a number of decimal places.

This is because in the operation of the first floating-point number into binary after the operation, but some decimal in the binary code after the infinite loop, resulting in the calculation of errors, and other into the language has similar problems.

Reason explanation reference since Baidu knows:

For example: Ask 1038.1-1000
1038.1=10000001110.0001100110011001100110011001100110011001100 .....
1000 =1111101000

1038.1 Convert to binary is an infinite loop decimal, 1100 is the link, only approximate value, error is generated here if the browser version is high, you can use the tofixed () method to round the number to the specified decimal digits.

Solution: Depending on the number of decimal places to keep (such as 4), multiply the product by multiplying (10^4), then dividing the calculated result by (10^4), and then approximating the result Math.Round

Copy Code code as follows:

var m1 = 2232.00,
Percent = (10/100),
Total = percent*m1;
Alert (total);//223.20000000000002

Total = Math.Round (total*10)/10;
Alert (total);//223.2

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.