์ ํํ ๋ต์ด ํ์ํ๋ค๋ฉด float์ double์ ํผํ๋ผ.
float์ double ํ์
์ ๊ณผํ๊ณผ ๊ณตํ ๊ณ์ฐ์ฉ์ผ๋ก ์ค๊ณ๋์๋๋ฐ, ๋์ ๋ฒ์ ์๋ฅผ ๋น ๋ฅด๊ฒ ์ ๋ฐํ ๊ทผ์ฌ์น
๋ก ๊ณ์ฐํ๋๋ก ์ค๊ณ๋์๋ค.
๋๋ฌธ์ ๋ง์ฝ ์ ํํ ๋ต์ด ํ์ํ๋ค๋ฉด float์ double์ ํผํด์ผ ํ๋ค.
class Example {
public static void main(String[] args) {
System.out.println(1.03 - 0.42); // 0.6100000000000001
System.out.println(1.00 - 9 * 0.10); // 0.09999999999999998
double funds = 1.00;
int itemsBought = 0;
for (double price = 0.10; funds >= price; price += 0.10) {
funds -= price;
itemsBought++;
}
System.out.println(itemsBought + " items bought."); // 3 items bought.
System.out.println("Change: $" + funds); // Change: $0.3999999999999999
}
}
์ ๊ฒฐ๊ณผ๋ ๊ฐ๊ฐ 0.6, 0,1, 4, 0์ด ๋์ค๊ธธ ๊ธฐ๋ํ์ง๋ง ์์์ ์ ์ ํํ ํํํ์ง ๋ชปํด ์ค์ฐจ๊ฐ ๋ฐ์ํ๋ค.
์ด๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด์ BigDecimal
, int
, long
์ ์ฌ์ฉํด์ผ ํ๋ค.
class Example {
public static void main(String[] args) {
final BigDecimal TEN_CENTS = new BigDecimal(".10");
BigDecimal funds = new BigDecimal("1.00");
int itemsBought = 0;
for (BigDecimal price = new BigDecimal("0.10"); funds.compareTo(price) >= 0; price = price.add(new BigDecimal("0.10"))) {
funds = funds.subtract(price);
itemsBought++;
}
System.out.println(itemsBought + " items bought."); // 4 items bought.
System.out.println("Change: $" + funds); // Change: $0.00
}
}
class Example {
public static void main(String[] args) {
int itemsBought = 0;
int funds = 100;
for (int price = 10; funds >= price; price += 10) {
funds -= price;
itemsBought++;
}
System.out.println(itemsBought + " items bought."); // 4 items bought.
System.out.println("Change: $" + funds); // Change: $0
}
}