JS decimal calculation Why and imagine not the same!

Source: Internet
Author: User

today I met a more interesting thing, if you want to calculate 0.1+0.2 equals how much you will answer? "0.3 Ah!" "You may not even consider it. I am also the same when a=0.1,b=0.2 when the if (a+b = = = 0.3) {...}. I could wait a whole afternoon. The contents of the curly braces are executed.

   Why is it? Because of the 0.1+0.2=0.30000000000000004 in JS. You may not believe it or go to the test. So why is that? After I find the information, I suddenly see. For floating-point data, most language calculations lose precision. But a powerful language like C++/java has its own package of methods to solve this problem. JS belongs to the weakly typed interpretative language. We can make a product of this sentence.

Why do you lose precision? Then we found the computer, the computer said I only know the number of binary. Then we'll give him the binary number. The binary representation of 0.1 is an infinite loop of fractional 0.0001100110011001100 ...

the binary representation of 0.2 is 0.0011001100110011 ..., then the addition should also be an infinite loop of decimals! No, double-precision floating-point data takes up to 52 digits after the decimal point, so it is 0.010011001100110011001

01100110011001100110011001100, then the conversion to 10 binary is 0.30000000000000004. Is it clear why the accuracy was lost?

Although the accuracy will be lost, and JS does not have their own packaging solutions, but these are not good, because I believe that all the problems have a corresponding solution. There are too many ways to solve JS. Through the API of the Math object. Through the tofixed of the number object. So these will not affect the charm of JS!

2017.8.24 Shanghai! 22:10

 

JS decimal calculation Why and imagine not the same!

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.