<p>EffecitveJava_对要求精确计算的场合不要使用double,float</p>
<p><textarea cols="50" rows="15" name="code" class="java:showcolumns">public static void doubleError() {
double founds = 1.00;// 口袋里一共有一块钱
int itemBought = 0;// 记录可以买几个糖果
for (double price = 0.1; founds >= price; price += 0.1) {// 糖果的价格依次曾加0.1
founds -= price;// 每次买一个,口袋里的钱就要花掉一些
itemBought++;// 每次买一个,手中糖果的数量增加一次
}
System.out.println(itemBought);
System.out.println(founds);
}
public static void bigDecimalSuccess() {
BigDecimal founds = new BigDecimal("1.00");// 口袋里一共有一块钱
BigDecimal TEN_CENTS = new BigDecimal("0.1");
int itemBought = 0;// 记录可以买几个糖果
for (BigDecimal price = TEN_CENTS; founds.compareTo(TEN_CENTS) >= 0; price = price
.add(TEN_CENTS)) {// 糖果的价格依次曾加0.1
founds = founds.subtract(price);// 每次买一个,口袋里的钱就要花掉一些
itemBought++;// 每次买一个,手中糖果的数量增加一次
}
System.out.println(itemBought);
System.out.println(founds.doubleValue());
}</textarea></p>
<p><textarea cols="50" rows="15" name="code" class="java:showcolumns">public static void doubleError() {
double founds = 1.00;// 口袋里一共有一块钱
int itemBought = 0;// 记录可以买几个糖果
for (double price = 0.1; founds >= price; price += 0.1) {// 糖果的价格依次曾加0.1
founds -= price;// 每次买一个,口袋里的钱就要花掉一些
itemBought++;// 每次买一个,手中糖果的数量增加一次
}
System.out.println(itemBought);
System.out.println(founds);
}
public static void bigDecimalSuccess() {
BigDecimal founds = new BigDecimal("1.00");// 口袋里一共有一块钱
BigDecimal TEN_CENTS = new BigDecimal("0.1");
int itemBought = 0;// 记录可以买几个糖果
for (BigDecimal price = TEN_CENTS; founds.compareTo(TEN_CENTS) >= 0; price = price
.add(TEN_CENTS)) {// 糖果的价格依次曾加0.1
founds = founds.subtract(price);// 每次买一个,口袋里的钱就要花掉一些
itemBought++;// 每次买一个,手中糖果的数量增加一次
}
System.out.println(itemBought);
System.out.println(founds.doubleValue());
}</textarea></p>