【问题标题】:Java NumberFormat generates 'EUR' instead of €Java NumberFormat 生成 'EUR' 而不是 €
【发布时间】:2012-07-09 10:26:57
【问题描述】:

我正在开发一个支持多种用户语言的安卓应用。

在应用程序中,我使用 java.util.NumberFormat 来格式化货币:

String formatCurrency(String amount) {
    // getCurrentLocale determines the locale from the user's selected language; 
    // if the user selects de_DE as the app's language, then this method will return Locale.Germany
    final Locale locale = getCurrentLocale(); 
    final NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
    return formatter.format(new BigDecimal(amount));
}

我正在使用的测试设备是 HTC G2,它有两种设备语言选项 - 英语和西班牙语。

好的,现在我为我的应用选择用户语言为“de_DE”:

// When my device language is english, if I call:
System.out.println(formatCurrency("1.79"));
// I got:
1.79 €

// But when I switch my device language to spanish:
System.out.println(formatCurrency("1.79"));
// I got :
1.79 EUR

我的问题是,在这两种情况下,我可以让 NumberFormat 给我 € 吗?

【问题讨论】:

    标签: android currency number-formatting


    【解决方案1】:

    为什么不总是使用您希望在其中显示的Locale?忽略设备的Locale

    对于Locale.ENGLISH

    String formatCurrency(String amount) {
        final NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.ENGLISH);
        return formatter.format(new BigDecimal(amount));
    }
    

    【讨论】:

    • 是的,我在代码中忽略了设备的区域设置,但是当我切换设备的语言时,NumberFormat 似乎并没有 100% 忽略它。例如,作为一个实验,我写了这样的东西:
    • 打电话给getCurrentLocale() 做什么?听起来用户的语言环境并没有从它上面的评论中被忽略:)。
    • 它获取用户选择的语言并将其映射到对应的语言环境。例如,'en_US' 到 Locale.ENGLISH 和 'fr_FR' 到 Locale.FRANCE @cklab
    • 对...所以我说不要使用那个区域设置。
    • Urrr,我必须使用该语言环境,这样才能以正确的方式格式化货币。当用户选择德语作为语言时,就像 1.79 欧元而不是 1.79 美元一样。@cklab
    【解决方案2】:

    你应该看看this

    使用 Currency 对象中的 getSymbol() 来解决您的问题。

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 2022-06-24
      相关资源
      最近更新 更多