問題描述
我正在盡我最大的努力尋找一種方法,使用 Java 來在各種語言環境中格式化外幣,這些語言不是該貨幣的默認設置.我找到了 java.util.Currency,它可以代表用于各種語言環境的正確符號.也就是說,對于美元,它在美國為我提供符號 $,在其他國家提供美元或美元.此外,我還找到了 java.text.NumberFormat,它將為特定語言環境格式化貨幣.我的問題 - util.Currency 將提供適當的符號和代碼來表示其非默認語言環境中的貨幣,但不會以任何特定于語言環境的方式格式化貨幣.NumberFormat 假定我傳遞給它的數字(帶有語言環境)是該語言環境的貨幣,而不是外幣.
I'm doing my best to find a way to format foreign currencies across various locales which are not default for that currency, using Java. I've found java.util.Currency, which can represent the proper symbol to use for various locales. That is, for USD, it provides me the symbol $ in the US, and US$ or USD in other nations. Also, I've found java.text.NumberFormat, which will format a currency for a specific locale. My problem - util.Currency will provide proper symbols and codes for representing currencies in their non-default locales, but will not format currency in any locale-specific way. NumberFormat assumes that the number I pass it, with a locale, is the currency of that locale, not a foreign currency.
例如,如果我使用 getCurrencyInstance(Locale.GERMANY) 然后格式化 (1000) 它假定我正在格式化 1000 歐元.實際上,對于美元、日元或任何其他貨幣,我可能需要正確的德語本地化表示(正確的小數和千位分隔符,無論是在金額之前還是之后放置符號).到目前為止,我能夠得出的最好的結果是使用 NumberFormat 格式化數字,然后在輸出中搜索非數字字符并將它們替換為從 util.Currency 派生的符號.但是,這非常脆弱,對于我的目的來說可能不夠可靠.想法?任何幫助深表感謝.
For example, if I use getCurrencyInstance(Locale.GERMANY) and then format (1000) it assumes I am formatting 1000 euro. In reality, I may need the correct German-localized representation (correct decimal and thousands separator, whether to put the symbol before or after the amount) for USD, or Yen, or any other currency. The best I've been able to derive so far is to format a number using NumberFormat, then search the output for non-digit characters and replace them with symbols derived from util.Currency. However, this is very brittle, and probably not reliable enough for my purposes. Ideas? Any help is much appreciated.
推薦答案
嘗試使用setCurrency 在 getCurrencyInstance(Locale.GERMANY) 返回的實例上
Try using setCurrency on the instance returned by getCurrencyInstance(Locale.GERMANY)
壞了:
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.GERMANY);
System.out.println(format.format(23));
產出:23,00 歐元
Output: 23,00 €
固定:
java.util.Currency usd = java.util.Currency.getInstance("USD");
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.GERMANY);
format.setCurrency(usd);
System.out.println(format.format(23));
產出:23,00 美元
Output: 23,00 USD
這篇關于在 Java 中的外國語言環境中格式化貨幣的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!