Home >Java >javaTutorial >Item Avoid float and double if exact answers are required
Problem with float and double:
Example 1:
Incorrect calculation when subtracting dollar amounts:
System.out.println(1.03 - 0.42); // Resultado: 0.6100000000000001
Example 2:
Error when purchasing nine items for 10 cents each:
System.out.println(1.00 - 9 * 0.10); // Resultado: 0.09999999999999998
Even rounding, errors persist.
Problem with progressive calculations, such as when purchasing sweets at incremental prices of 0.10 to 1.00.
Example 3:
Mistake when buying sweets until you have no more money:
double funds = 1.00; for (double price = 0.10; funds >= price; price += 0.10) { funds -= price; } System.out.println(funds); // Resultado: 0.3999999999999999
Solution 1: Use BigDecimal
Example with 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
The calculation is now precise.
Disadvantages of BigDecimal:
Solution 2: Use int or long
Example with int (in cents):
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
The calculation is fast and accurate.
Conclusion:
Choices:
The above is the detailed content of Item Avoid float and double if exact answers are required. For more information, please follow other related articles on the PHP Chinese website!