Javascript multiplying incorrectly, causing incorrect rounding

后端 未结 3 1886
名媛妹妹
名媛妹妹 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:11

    JavaScript/TypeScript have only one Number class which is not that good. I have the same problem as I am using TypeScript. I solved my problem by using decimal.js-light library.

    new Decimal(78).mul(7).mul(0.0725) returns as expected 39.585
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 00:31

    You might find the Accounting.js library useful for this. It has an "improved" toFixed() method.

    0 讨论(0)
提交回复
热议问题