浮动和双精度问题:
示例1:
减去美元金额时计算错误:
system.out.println(1.03 - 0.42); // resultado: 0.6100000000000001
示例2:
以每件 10 美分的价格购买 9 件商品时出错:
system.out.println(1.00 - 9 * 0.10); // resultado: 0.09999999999999998
即使四舍五入,错误仍然存在。
累进计算存在问题,例如以 0.10 到 1.00 的增量价格购买糖果时。
示例 3:
没钱买糖果时犯的错误:
double funds = 1.00; for (double price = 0.10; funds >= price; price += 0.10) { funds -= price; } system.out.println(funds); // resultado: 0.3999999999999999
解决方案 1:使用 bigdecimal
bigdecimal 示例:
bigdecimal funds = new bigdecimal("1.00"); bigdecimal price = new bigdecimal("0.10"); int itemsbought = 0; while (funds.compareto(price) >= 0) { funds = funds.subtract(price); price = price.add(new bigdecimal("0.10")); itemsbought++; } system.out.println(itemsbought + " items bought. money left: " + funds); // resultado: 4 items bought. money left: 0.00
计算现在很精确。
bigdecimal 的缺点:
解决方案 2:使用 int 或 long
int 示例(以分为单位):
int funds = 100; // 1.00 dólar = 100 centavos int price = 10; // 0.10 dólar = 10 centavos int itemsBought = 0; while (funds >= price) { funds -= price; price += 10; itemsBought++; } System.out.println(itemsBought + " items bought. Money left: " + funds); // Resultado: 4 items bought. Money left: 0
计算又快又准。
结论:
选择: