2012-05-31 76 views
11

有一些現有它用於格式數值後續形式的代碼的Java的String.format與貨幣符號

String.format(pattern, value) 

注意,我不能改變代碼本身 - 我只能更改提供給代碼的格式模式。

什麼是輸出默認語言環境的貨幣符號的格式模式?從本質上講,我想實現以下的輸出:

String.format("...", 123) => $ 123 
+0

也許值得看一看[NumberFormat的(http://docs.oracle.com/javase/6/docs/api/java/text/NumberFormat.html#format (長))。 –

+0

編輯提到我不能更改代碼 –

+0

@MarcPolizzi:你不能改變代碼,但你*可以*改變格式字符串(大概在別處指定) - 是嗎? –

回答

4

由於您提出的限制,我認爲這是不可能實現的。 要獲得當前的區域設置的貨幣符號,您需要最少的代碼。

如果您完全沒有辦法向程序添加代碼,則最好使用「currency」(¤)的已建立符號。它是爲了這個確切的目的而建立的,以表示沒有任何更具體的符號的貨幣。

如果您不能更改給定的代碼,但將代碼作爲整體添加到項目中,則可以使用該代碼找出最適合使用的符號。一旦擁有了它,就可以使用它爲現有代碼創建格式化模式。

如果您可以找出原始程序將在下一個運行的語言環境中,則可以編寫一個使用該設置填充配置的助手程序。

4

你可以嘗試以下方法:

public static void main(String[] args) { 
    System.out.println(String.format(" %d \u20AC", 123)); // %d for integer 
    System.out.println(String.format(" %.2f \u20AC", 123.10)); // %f for floats 
} 

此打印:

123 € 
123.10 € 
-2
String formatstring=String.format("$%s", 123); 
    System.out.println(formatstring); 
+0

如果我的JVM的本地語言爲法語,似乎不打印歐元符號;仍然顯示$ –

+0

ohhh對不起。我以爲你想打印$。 –

11

無需推倒重來。 DecimalFormat配備了貨幣支持:

String output = DecimalFormat.getCurrencyInstance().format(123.45); 

這也可任選地使在Locale配備了完整的語言環境支持:

String output = DecimalFormat.getCurrencyInstance(Locale.GERMANY).format(123.45); 

這是一個測試:

System.out.println(DecimalFormat.getCurrencyInstance().format(123.45)); 
System.out.println(DecimalFormat.getCurrencyInstance(Locale.GERMANY).format(123.45)) ; 

輸出:

$123.45 
123,45 € 
1

如果沒有默認的Locale可用,我們可以使用unicode和decimal格式設置貨幣符號。如下面的代碼:

例如,設置印度貨幣符號並設置其值。這將在用戶無需更改設置的情況下運行。

Locale locale = new Locale("en","IN"); 
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale); 
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale); 
dfs.setCurrencySymbol("\u20B9"); 
decimalFormat.setDecimalFormatSymbols(dfs); 
System.out.println(decimalFormat.format(12324.13)); 

輸出:

₹12,324.13