ToFixed uses the banker rounding rule in javascript.
Banker rounding: a rounding of four to five (also known as rounding six to five to keep two) method.
In simple terms is: four rounding six into five, five non-zero into one, five after zero to see odd even, five before even should be dropped, five before strange to enter a. However, whether toFixed is introduced to solve the problem of missing accuracy of floating-point calculation, or whether it uses banker rounding method or not, both aim to solve the problem of accuracy, but can not leave the binary floating-point environment, but at least it helps us find the problem, so that we have a solution.
One: Rounding is not really rounding
This question was raised by our testers during the testing phase. I was surprised at first, but after I tried some data on the console, I was stunned that the toFixed method I had been using was not working
Test results on Chrome:
ToFixed (1) // 1.4 correct 1.335.toFixed(2) // 1.33 error 1.3335. ToFixed (3) // 1.333 Error 1.33335.toFixed(4) // 1.3334 correct 1.333335. ToFixed (5) // 1.33333 error 1.3333335Copy the code
Test results on IE:
1.35. ToFixed (1) // 1.4 correct 1.335. ToFixed (2) // 1.34 correct 1.3335. ToFixed (3) // 1.334 correct 1.33335 1.333335.toFixed(5) // 1.33334 correct 1.333333335Copy the code
The solution
let str = ""; // String sum STR = (math.round (num * 100) / 100).tofixed (2).toString().replace(/(\d)(? =(\d{3})+\.) /g, function($0, $1) { return $1 + ","; }); return str; // String => array => reverse => string}Copy the code