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