A realistic example where using BigDecimal for currency is strictly better than using double

前端 未结 8 2029
野趣味
野趣味 2020-12-13 06:29

We know that using double for currency is error-prone and not recommended. However, I\'m yet to see a realistic example, where BigDecimal

8条回答
  •  离开以前
    2020-12-13 06:36

    The main problems you are facing in practice are related to the fact that round(a) + round(b) is not necessarily equal to round(a+b). By using BigDecimal you have fine control over the rounding process and can therefore make your sums come out correctly.

    When you calculate taxes, say 18 % VAT, it is easy to get values that have more than two decimal places when represented exactly. So rounding becomes an issue.

    Lets assume you buy 2 articles for $ 1.3 each

    Article  Price  Price+VAT (exact)  Price+VAT (rounded)
    A        1.3    1.534              1.53
    B        1.3    1.534              1.53
    sum      2.6    3.068              3.06
    exact rounded   3.07
    

    So if you do the calculations with double and only round to print the result, you would get a total of 3.07 while the amount on the bill should actually be 3.06.

提交回复
热议问题