Calculation accuracy of floating-point numbers in JS

Source: Internet
Author: User

The accuracy of floating-point numbers in JS can generally reach 16 digits, so some people use parsefloat (x.tofixed (12)) to improve the precision of the floating-point arithmetic in JS.

It is proved that this method is basically correct when the number of digits is small, but it is not valid for large or small operation results, such as 1222.31*2344, the direct operation result is 2865094.6399999997, parsefloat (1222.31* 2344). ToFixed (12)) is still 2865094.6399999997and does not improve accuracy.

At this point, the results should be normalized before the tofixed (12) Such processing, can guarantee 12 digits of valid numbers, the following is the processing of the results of large operations:

function accurate (x) {  var factor = Math.pow (Ten, Math.Abs (x). ToString (). Split ('. ') [0].length + 1);  Return (X/factor). toFixed (n) * factor;} Accurate (1222.31*2344);//Output 2865094.64

For a smaller number, you need to find its first non-0 decimal place (assuming it is the nth digit after the decimal point), then multiply by a 10 N-second square, then tofixed (12), divided by the n-th of 10.

Calculation accuracy of floating-point numbers in JS

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.