Home  >  Article  >  Web Front-end  >  Solution to multiple decimal places in Javascript floating-point product operation_javascript skills

Solution to multiple decimal places in Javascript floating-point product operation_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:59:491645browse

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

This is because the floating-point numbers are first converted into binary before calculation. However, some decimals appear in infinite loops after binary encoding, which leads to errors in calculations. This is also the case in other programming languages. Similar questions.

The explanation of the reason is known from Baidu:

For example: find 1038.1-1000
1038.1=10000001110.0001100110011001100110011001100110011001100....
1 000 =1111101000

1038.1 conversion Binary is an infinitely recurring decimal, and 1100 is a cyclic section. Only approximate values ​​can be taken. The error is caused here. If the browser version is high, you can use the toFixed() method to round the Number to a number with specified decimal places.

Solution: According to the number of decimal places to be retained (such as 4), first multiply by (10^4) when calculating the product, then divide the calculation result by (10^4), and finally divide the result Take the approximate value Math.round

Copy code The code is 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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn