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