2012-11-01 31 views
5

我想避免使用區域設置,而是使用貨幣代碼(ISO 4217,如「USD」)。我瞭解如何使用貨幣代碼設置貨幣類,但是,如何將此貨幣合併爲一個NumberFormat以將貨幣格式化爲所述貨幣?如何將ISO4217貨幣代碼提供給NumberFormat?

我同時理解NumberFormat和Currency,但是怎樣才能將這些格式化爲真正的貨幣字符串,例如4.00 - > $ 4.00?我必須使用NumberFormat,因爲我在本例中刪除了小數位數來創建整個貨幣數字,例如$ 4。

感謝你的幫助, 瑞安

編輯:回答,.setCurrency,這是我沒有注意到的NumberFormat,衛生署!我太專注於用貨幣構造NumberFormat,但我一直在掙扎,因爲您只能從Locale構造。希望我早點想到這一點。謝謝!下次我將閱讀更接近的方法列表。我知道NumberFormat HAD支持貨幣類,它只有在這種方式下使用貨幣纔有意義。

+0

請不要評論我使用雙打貨幣,我不需要精確度。謝謝。 – AutoM8R

回答

3

這應該讓您顯示給定貨幣的金額到最近的整個貨幣單位。我還沒有測試過,但認爲這是95%的權利。

double amount = ...; 
String currencyCode = ...; 
Currency currency = Currency.getInstance(currencyCode); 
NumberFormat format = NumberFormat.getCurrencyInstance(); 
format.setMaximumFractionDigits(0); 
format.setCurrency(currency); 
String formattedAmount = format.format(amount); 
2

你試過下面的代碼:

NumberFormat nf = NumberFormat.getCurrencyInstance(); 
    String currencyCode = "USD"; 
    nf.setCurrency(Currency.getInstance(currencyCode)); 
    double currencyAmmount = 4.00; 
    String formattedValue= nf.format(currencyAmmount); 

從上面的代碼我$4.00,我以爲這是你所期望的。

我想這裏最重要的是使用NumberFormat.getCurrencyInstance()而不是NumberFormat.getInstance()

+0

謝謝你,另一個有效的答案。你剛剛錯過了我放棄小數的事實。 – AutoM8R