broken toFixed implementation

后端 未结 6 2220
陌清茗
陌清茗 2020-11-27 21:51

The default implementation of javascript\'s \"Number.toFixed\" appears to be a bit broken.

console.log((8.555).toFixed(2));    // returns 8.56
console.log((         


        
6条回答
  •  甜味超标
    2020-11-27 22:23

    This is because of floating-point errors.

    Compare (8.575).toFixed(20) with (8.575).toFixed(3) and imagine this proposition: 8.575 < real("8.575"), where real is an imaginary function that creates a real number with infinite precision.

    That is, the original number is not as expected and the inaccuracy has already been introduced.

    One quick "workabout" I can think of is: Multiply by 1000 (or as appropriate), get the toFixed(0) of that (still has a limit, but it's absurd), then shove back in the decimal form.

    Happy coding.

提交回复
热议问题