不同于 Locale 的货币的货币格式

pde*_*d59 4 java android

在 Android 上,我试图用特定的数字格式格式化一些货币。

我的号码必须使用法语格式 ( 9 876 543,21)进行格式化,但应根据货币放置货币符号:

  • 9 876 543,21 € 欧元
  • $9 876 543,21 美元

这是我现在的代码(这使用了java.util类,但结果与android.icu包相同):

final Double of = Double.valueOf("9876543.21");
final Currency usd = Currency.getInstance("USD");
final NumberFormat currencyInstance = NumberFormat.getCurrencyInstance(Locale.FRANCE);
currencyInstance.setCurrency(usd);
Log.d("test", currencyInstance.format(amount));
Run Code Online (Sandbox Code Playgroud)

输出是9 876 543,21 $US因为我的 NumberFormat 使用的是法语语言环境。

注意:Locale 必须是 FRANCE(或 FRENCH)才能获得良好的数字格式,而且我实际上不知道货币代码(例如 EUR、USD 或 GBP),它只是来自网络服务的字符串。

有没有办法告诉格式化程序我想要法语数字格式,但它需要尊重符号的货币位置?

Tia*_*ira 6

这很完美,我认为这就是您想要实现的目标

    final Double of = Double.valueOf("9876543.21");

    NumberFormat currencyInstance = NumberFormat.getCurrencyInstance(getLocalFromISO("EUR"));
    Log.d("test", currencyInstance.format(of));
    currencyInstance = NumberFormat.getCurrencyInstance(getLocalFromISO("GBP"));
    Log.d("test", currencyInstance.format(of));
    currencyInstance = NumberFormat.getCurrencyInstance(getLocalFromISO("SEK"));
    Log.d("test", currencyInstance.format(of));
    currencyInstance = NumberFormat.getCurrencyInstance(getLocalFromISO("USD"));
    Log.d("test", currencyInstance.format(of));

private Locale getLocalFromISO(String iso4217code){
    Locale toReturn = null;
    for (Locale locale : NumberFormat.getAvailableLocales()) {
        String code = NumberFormat.getCurrencyInstance(locale).
                getCurrency().getCurrencyCode();
        if (iso4217code.equals(code)) {
            toReturn = locale;
            break;
        }
    }
    return toReturn;
}
//Prints  
//9.876.543,21 €
//£9,876,543.21
// 9 876 543,21 kr
//US$9,876,543.21
Run Code Online (Sandbox Code Playgroud)