How to format double value for a given locale and number of decimal places?

后端 未结 4 1650
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 15:27

How can I use NumberFormat to format a double value for a given Locale (default locale is sufficient) and for a given number of decima

4条回答
  •  一生所求
    2020-12-17 15:33

    If you care to read NumberFormat's documentation, the solution would be obvious:

    double d1 = 123456.78;
    double d2 = 567890;
    // self commenting issue, the code is easier to understand
    Locale fmtLocale = Locale.getDefault(Category.FORMAT);
    NumberFormat formatter = NumberFormat.getInstance(fmtLocale);
    formatter.setMaximumFractionDigits(2);
    formatter.setMinimumFractionDigits(2);
    System.out.println(formatter.format(d1));
    System.out.println(formatter.format(d2));
    System.out.println(fmtLocale.toLanguageTag());
    

    On my machine this prints out:

    123 456,78
    567 890,00
    pl-PL

    I believe this is what you are looking for, and you don't have to mess-up with patterns. I wouldn't do that - for instance there are locales which group digits by two, not by three (this is the reason we talk about grouping separator and not thousands separator).

提交回复
热议问题