Mysterious calculation error when multiply by 100

后端 未结 2 1350
时光取名叫无心
时光取名叫无心 2020-12-07 02:21

The following script contains a very strange error. I want to check if a value is a positive integer. To do this, I multiply by 100 to enclose the value to decimal. If I tes

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 03:01

    That's because javascript casts everything to a double internally. As a result, all calculations pick up some noise due to floating point inaccuracy: Floating point inaccuracy examples

    One way to fix this issue, is to just round down to the nearest int after all intermediate calculations.

提交回复
热议问题