The accuracy of JS floating-point number

Source: Internet
Author: User

Floating-point number implementation principle, determines the floating point will have a tragedy, that is to calculate the value of 0.3 + 0.3 + 0.3, you can print the results in the console, his value is not what you expect 0.9, but the ugly 0.899999999999999

How to deal with this situation.

Now available in 3 different scenarios

1, no processing. Why don't you have to deal with that? Since 0.8999999999999999 and 0.9 do not have an essential difference when used.

2, display time processing. If you want to present the results of 0.3+0.3+0.3 in front of the user, the ugly 0.8999999999999999 is obviously not the result you expect. What you're looking for is 0. 9. How to render 0.9? Then the final result plus a patch that doesn't seriously affect the authenticity of the results. See if the number of floating-point numbers has changed since the patch was added, and if a big change has taken place, congratulations, you've added the right patch.

3, calculation when processing, if you can control the calculation process, then you can take the following approach, such as the calculation of 0.3+0.3+0.3, you can get the final result var a = 0.3*10+0.3*10+0.3*10;a = A/10; This method I am very not respected, Because he is confused with the concept of methods, despise the practice of pre-cow custom norms!!!

4, you have a very high accuracy requirements, well, float type (for the moment "type" this inappropriate word) has not been suitable for you, you should implement a new high-precision type. The specific plan here will not say, but this has been achieved such a business is not suitable for the JS language.

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.