在Java应用程序中处理多种货币
我希望能够在我的应用程序中处理多种货币。我有一个创建事务实例的方法:在Java应用程序中处理多种货币,java,Java,我希望能够在我的应用程序中处理多种货币。我有一个创建事务实例的方法: class MyApp() { //... public Transaction createTransaction(String desc, BigDecimal amount) {... 这就是所谓的: createTransaction("Phone bill", new BigDecimal("28.555")); 但是,我希望金额的格式取决于货币/区域设置。我在想有点像: interface My
class MyApp() {
//...
public Transaction createTransaction(String desc, BigDecimal amount) {...
这就是所谓的:
createTransaction("Phone bill", new BigDecimal("28.555"));
但是,我希望金额的格式取决于货币/区域设置。我在想有点像:
interface MyCurrency() {
public static BigDecimal format(BigDecimal amount);
}
public class GBP implements MyCurrency {
public static BigDecimal format(BigDecimal amount) {
return amount.setScale(2, BigDecimal.ROUND_FLOOR); // 28.555 -> 28.55
}
}
public class JPY implements MyCurrency {
public static BigDecimal format(BigDecimal amount) {
return amount.setScale(0, BigDecimal.ROUND_FLOOR); // 28.555 -> 28
}
}
// then modify my app class as follows
class MyApp() {
//...
public void setCurrency(MyCurrency currency) {
this.currency = currency;
}
public Transaction createTransaction(String desc, BigDecimal amount) {
amount = this.currency.format(amount);
//...
}
我希望这是有道理的。但是,是否有一个Java构建来实现这一点?我搜索了处理多种货币的方法,但没有找到任何讨论这一点的内容(我确信这是一种非常常见的情况)您尝试过以下方法吗?它根据显示货币的国家/地区的数字规格设置货币格式
java.util.Currency usd = java.util.Currency.getInstance("USD");
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.GERMANY);
format.setCurrency(usd);
format.setMaximumFractionDigits(usd.getDefaultFractionDigits());
System.out.println(format.format(23));
除非你的意思是,在德国应该是欧元,在英国应该是英镑。在这种情况下,你应该澄清你的问题
但如果是这样的话:
DecimalFormat.getCurrencyInstance().format( 123.45);// $123.45
DecimalFormat.getCurrencyInstance(Locale.GERMANY).format( 123.45); // 123,45 €
记住这一点:实际上并没有单位数。如果要创建交易,则需要指定交易所用的货币(单位)。你需要在任何地方存储这些信息,等等。