Title: Suppose you have 1$ in your pocket and see a row of delicious candies on the shelves, priced at 0.10$,0.20$,0.30$ ... 1$, you plan to buy from the price of 0.10$ candy, each buy one, until you can not pay the price of the shelves at the end of the candy, so how many sweets? How much change can I get back?
The procedure for using double is as follows:
Double funds = 1.00;int Itemsbought = 0;for (double price=.10;funds>=price;price+=.10) {funds-= Price ; itemsbought++;} System.out.println (itemsbought+ "items bought."); System.out.println ("change:$" +funds);
The returned results are as follows:
3 items bought.
change:$0.3999999999999999
The answer is not correct, and the solution is to use bigdecimal,int or long for currency calculations
The procedure for using BigDecimal is as follows:
Final BigDecimal ten_cents = new BigDecimal (". ten"); int itemsbought = 0; BigDecimal funds = new BigDecimal ("1.00"); for (BigDecimal Price=ten_cents;funds.compareto (price) >=0;price= Price.add (ten_cents)) { itemsbought++; Funds = Funds.subtract (price);} System.out.println (itemsbought+ "items bought."); System.out.println ("change:$" +funds);
The returned results are as follows:
4 items bought.
Change:$0
The result is correct.
The program that uses int is as follows (1.00$ must be converted to 100cents first):
int itemsbought = 0;int funds = 100;for (int price=10;funds>=price;price+=10) {funds-= Price ; itemsbought++;} System.out.println (itemsbought+ "items bought."); System.out.println ("change:$" +funds);
The returned results are as follows:
4 items bought.
Change:$0
The result is also correct.
So:
1) It is very convenient to use BigDecimal if it is necessary to conduct business calculations with the required rounding behavior;
2) If performance is critical, and you do not mind recording decimal points, and the values involved are not too large, you can use int or long,
3) If the range of values does not exceed 9 decimal digits, you can use int, if the range of values does not exceed 18 decimal digits, you can use long if the range of values exceeds 18 decimal digits, you must use BigDecimal.
Effective Java-----Precise answers and double&float