【问题标题】:Use DecimalFormat(#.#) with localization使用 DecimalFormat(#.#) 进行本地化
【发布时间】:2016-08-27 16:42:17
【问题描述】:

我可以轻松地使用DecimalFormat 来格式化我的数字。示例

 DecimalFormat format = new DecimalFormat("#.#");

但是,我需要传递这个数字,以便像这样通过本地化来格式化

        DecimalFormat english = (DecimalFormat)DecimalFormat.getNumberInstance(Locale.ENGLISH);

如何将两者结合起来?谢谢。

【问题讨论】:

    标签: java android decimalformat


    【解决方案1】:

    您指定要使用的DecimalFormatSymbols

    DecimalFormatSymbols symbolsEN_US = DecimalFormatSymbols.getInstance(Locale.US);
    DecimalFormat formatEN_US = new DecimalFormat("#,###.#", symbolsEN_US);
    System.out.println(formatEN_US.format(-123456.789)); // prints -123,456.8
    
    DecimalFormatSymbols symbolsDE_DE = DecimalFormatSymbols.getInstance(Locale.GERMANY);
    DecimalFormat formatDE_DE = new DecimalFormat("#,###.#", symbolsDE_DE);
    System.out.println(formatDE_DE.format(-123456.789)); // prints -123.456,8
    
    DecimalFormatSymbols symbolsFR_FR = DecimalFormatSymbols.getInstance(Locale.FRANCE);
    DecimalFormat formatFR_FR = new DecimalFormat("#,###.#", symbolsFR_FR);
    System.out.println(formatFR_FR.format(-123456.789)); // prints -123 456,8
    
    DecimalFormatSymbols symbolsIT_CH = DecimalFormatSymbols.getInstance(Locale.forLanguageTag("it-CH"));
    DecimalFormat formatIT_CH = new DecimalFormat("#,###.#", symbolsIT_CH);
    System.out.println(formatIT_CH.format(-123456.789)); // prints -123'456.8
    
    DecimalFormatSymbols symbolsHI_IN = DecimalFormatSymbols.getInstance(Locale.forLanguageTag("hi-IN"));
    DecimalFormat formatHI_IN = new DecimalFormat("#,###.#", symbolsHI_IN);
    System.out.println(formatHI_IN.format(-123456.789)); // prints -१२३,४५६.८
    
    DecimalFormatSymbols symbolsTHAI = DecimalFormatSymbols.getInstance(Locale.forLanguageTag("th-TH-u-nu-thai-x-lvariant-TH"));
    DecimalFormat formatTHAI = new DecimalFormat("#,###.#", symbolsTHAI);
    System.out.println(formatTHAI.format(-123456.789)); // prints -๑๒๓,๔๕๖.๘
    

    【讨论】:

    • 不错的解决方案:)
    【解决方案2】:

    在这里找到答案: https://www.iro.umontreal.ca/~vaucher/Java/tutorials/Formatting.html

    就在 DecimalFormat 对象之前的Locale.setDefault(Locale.ENGLISH);

    Locale.setDefault(Locale.ENGLISH);
    DecimalFormat format = new DecimalFormat("#.#");
    

    【讨论】:

    • 如果您在多线程应用程序中需要多个区域设置,这将不起作用。
    猜你喜欢
    • 2010-11-16
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多