Home >Web Front-end >JS Tutorial >How to solve problems caused by toFixed() method in JS_javascript skills
Recently, I discovered that there are some problems with the toFixed() method in JS. When using the toFixed() method on the prototype object of the native Number object, the rule is not the so-called "rounding" or "rounding to five", the so-called " "Round up to six and round up to five to make even", the explanation given on Baidu Encyclopedia is: that is, "round up 4 to 6 and round up to 5 to make even" where "four" means rounding off when ≤ 4, and "six" means rounding when ≥ 6 Above, "five" refers to the number after 5. When there is a number after 5, 5 is rounded up to 1; when there is no valid digit after 5, two situations need to be considered: ① If the number before 5 is an odd number, round 5 Enter 1; ②The number before 5 is an even number, and 5 will not be rounded. (0 is the smallest even number). Several examples mentioned on Baidu Encyclopedia are indeed true in actual situations, but they are not scientific and cannot cover all situations.
Test browsers: Diaosi browser IE6 and advanced Diaosi browser IE78 and all modern mainstream browsers including IE9, IE10, FF, chrome, opera, and safari. (Note: When using IE10-like firebug development tools, the test results when using the compatible IE lower version browser mode are inconsistent with the test results using the native lower version IE browser)
At the end of the floating point number ≤ There is no controversy about rounding when the number is 4 or ≥ 6, but it is extremely confusing when the end is exactly equal to 5.
Summary: As we all know, floating-point calculations in languages that follow the IEEE754 numerical format will suffer from precision loss. ES is not alone in this problem, so try not to test a specific floating-point value, such as: 0.1 0.2;
Solution: Override the Number.prototype.toFixed() method: