Javascript multiplying incorrectly, causing incorrect rounding

后端 未结 3 1918
名媛妹妹
名媛妹妹 2021-01-02 23:54

When I pull the values I want to multiply, they\'re strings. So I pull them, parse them as floats (to preserve the decimal places), and multiply them together.



        
3条回答
  •  无人及你
    2021-01-03 00:27

    Floating points are represented in binary, not decimal. Some decimal numbers will not be represented precisely. And unfortunately, since Javascript only has one Number class, it's not a very good tool for this job. Other languages have decent decimal libraries designed to avoid precisely this kind of error. You're going to have to either accept one-cent errors, implement a solution server-side, or work very hard to fix this.

    edit: ooh! you can do 78 * 7 * 725 and then divide by 10000, or to be even more precise just put the decimal point in the right place. Basically represent the tax rate as something other than a tiny fraction. Less convenient but it'll probably take care of your multiplication errors.

提交回复
热议问题