1

I would like to use DecimalFormat with a custom pattern. The pattern can be set using the applyPattern() method, but this is not possible for Numberformat, so the DecimalFormat has to be used. However, the use of DecimalFormat is not possible without providing a locale and it then uses the locale setting to apply the locale-specific patter on top of the custom pattern. So, in essence the output is changed and does not meet the specifics of the supplied pattern anymore.

The case has been brought up before, but no solution that would us: DecimalFormat ignores given pattern but uses Locale

Is there a way to have strict use of a custom pattern without any automatic locale formatting magic? Thanks.

martin_wun
  • 1,599
  • 1
  • 15
  • 33
  • 3
    Could you give a concrete example of what you're trying to achieve, as a [mcve], showing your expected output and actual output? I'm finding it hard to understand exactly what you're looking for. – Jon Skeet Oct 02 '19 at 10:59
  • 1
    What’s wrong with the solution given in the answer to the question that you are linking to? Or more precisely, in which way doesn’t it solve your problem? – Ole V.V. Oct 02 '19 at 11:32

1 Answers1

1

Let me first check whether I understand your problem correcty.

    double number = 123456.789;
    NumberFormat nf = new DecimalFormat("###,###.###");
    System.out.println(nf.format(number));

This code uses your default FORMAT locale. When for example my default locale is set to German, the output is:

123.456,789

The German format symbols have been used: a dot as thousand separator and a comma as decimal “point”. You don’t want that.

The solution: I routinely use Locale.ROOT as “the locale neutral locale”, as a way to say “don’t perform any locale specific processing here”. It works here too. Change the instantiation of the formatter to:

    NumberFormat nf = new DecimalFormat("###,###.###", new DecimalFormatSymbols(Locale.ROOT));

Now the output — still in German locale — is:

123,456.789

Or a shorter and possibly better way to obtain the same result:

    NumberFormat nf = NumberFormat.getInstance(Locale.ROOT);

We don’t need to concern ourselves with DecimalFormat, just NumberFormat.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161