浮動小数点数がどのように機能するかをよく理解していないことに悩まされていることはほぼ確実です。10 進数で 1/3 を表すことができないのと同じように、2 進数で 0.1 を正確に表すことはできません。さらに、IEEE 浮動小数点数は倍精度で 17 桁を超える精度を持つことはできません。
Java やコードのバグではありません。
お金は、10 進数で表してはならないものの典型的な例です。
整数のドルとセントを使用して Money クラスを作成し、十分な Java を学習したときにそれを使用します。
public class Money {
private final int dollars;
private final int cents;
private final Currency currency;
public Money(int dollars, int cents, Currency curr) {
if (dollars < 0) throw new IllegalArgumentException("dollars cannot be negative");
if (cents < 0) throw new IllegalArgumentException("cents cannot be negative");
if (curr == null) throw new IllegalArgumentException("currency cannot be null");
this.dollars = dollars;
this.cents = cents;
this.currency = curr;
}
// more methods here.
}