A solution for the multiplication of JavaScript floating-point numbers with multiple decimal digits

Source: Internet
Author: User

This article mainly introduced the JavaScript floating-point number multiplication operation to appear many decimal places the solution method, needs the friend may refer to under

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 from Baidu know: For example: Beg 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, error is generated here if the browser version is high, you can use the tofixed () method to round the number to a specified decimal number. 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 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

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.