我建议对货币模式进行一些研究。Martin Fowler在他的《Analysis pattern》一书中更详细地介绍了这一点。
public class Money {
private static final Currency USD = Currency.getInstance("USD");
private static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN;
private final BigDecimal amount;
private final Currency currency;
public static Money dollars(BigDecimal amount) {
return new Money(amount, USD);
}
Money(BigDecimal amount, Currency currency) {
this(amount, currency, DEFAULT_ROUNDING);
}
Money(BigDecimal amount, Currency currency, RoundingMode rounding) {
this.currency = currency;
this.amount = amount.setScale(currency.getDefaultFractionDigits(), rounding);
}
public BigDecimal getAmount() {
return amount;
}
public Currency getCurrency() {
return currency;
}
@Override
public String toString() {
return getCurrency().getSymbol() + " " + getAmount();
}
public String toString(Locale locale) {
return getCurrency().getSymbol(locale) + " " + getAmount();
}
}
即将使用:
您将使用对象而不是 来表示所有资金。将货币表示为大十进制将意味着您将在显示货币的每个位置格式化货币。想象一下,如果显示标准发生变化。您将必须到处进行编辑。相反,使用这种模式,您可以将货币的格式集中到一个位置。Money
BigDecimal
Money
Money price = Money.dollars(38.28);
System.out.println(price);