How to solve multiple decimal places in the product operation of Javascript floating point number

Source: Internet
Author: User

Javascript performs the product operation of floating point numbers, and multiple decimal places may occur.

This is because the floating point number is converted into a binary number before the operation, but some decimals have an infinite loop after the binary encoding, resulting in an error in the calculation, similar problems occur in other languages.

For the reason, refer to Baidu:

For example: 1038.1-1000
1038.1 = 10000001110. 0001100110011001100110011001100110011001100 .....
1000 = 1111101000

Converting 1038.1 to binary is an infinite loop decimal, and 1100 is a loop section. Only approximate values can be taken. The error is generated here. If the browser version is high, you can use toFixed () you can rounding a Number to a Number with a specified Number of decimal places.

Solution: based on the number of decimal places (for example, 4) to be retained, multiply the product by (10 ^ 4), and then divide the calculation result by (10 ^ 4 ), math is the approximate value of the result. round
Copy codeThe Code is as follows:
Var m1 = 1, 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.