Home  >  Article  >  Web Front-end  >  Decimal calculation problems in JavaScript tutorial

Decimal calculation problems in JavaScript tutorial

巴扎黑
巴扎黑Original
2017-09-11 11:47:511882browse

First picture:

What's going on?

Reason: js uses binary for decimal calculations

First look at the method of converting decimal decimals into binary:

The integer digits of a decimal number are the integer digits of a binary number, decimal The decimal place of a number is the decimal place of a binary number

If we have a decimal 111.4 (10), we calculate it:

First take the decimal place 0.4 and "multiply it by two" Rounding method "

0.4*2=0.8 The number in the integer position of the result is 0                                                        | Shun

0.6 *2=1.2 Get 0 | Write

0.4*2=0.8 Get 0                                1                                                                                                                                                                                                                                                                                                                                                                    possible The binary number after the decimal point is

0.01100110... (Loop 0110)

I won’t write the integer, the method is to divide by 2 and take the remainder

In the question, 2.6+2.6+2.6 =7.800000000001. When calculating decimal operations in JavaScript, decimal decimals are first converted to the corresponding binary. Some decimals cannot be completely converted to binary. This is where the first error occurs. After all the decimals are converted to binary, operations between binary systems are performed to obtain the binary result. The binary result is then converted to decimal, where a second error usually occurs.

Solution: Specify how many decimal places to keep (7.8).toFixed(2)=7.80;. This method may lose accuracy. There are also ways to customize this addition online.

The above is the detailed content of Decimal calculation problems in JavaScript tutorial. For more information, please follow other related articles on the PHP Chinese website!

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