Matthias M
Matthias M

Reputation: 14850

DecimalFormat ignores given pattern but uses Locale

I want to format a number by a given format string using DecimalFormat. This is documented in the oracle java docs.

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
     DecimalFormat myFormatter = new DecimalFormat(pattern);
     String output = myFormatter.format(value);
     System.out.println(value + "  " + pattern + "  " + output);
  }

  static public void main(String[] args) {
    customFormat("###,###.###", 123456.789);
   }
}

But my output is German format style on my German os:

actual: 123456.789  ###,###.###  123.456,789
expected: 123456.789  ###,###.###  123,456.789

I know that I can explicitly set the separators. But I want to be able to set the format by a string like in the oracle docs. This should be independent of my os locale.

Upvotes: 3

Views: 1516

Answers (1)

Michael Peacock
Michael Peacock

Reputation: 2104

Since your default locale is German, you're getting the German number format. If you wish to change that select a different locale for the numberformat underlying your DecimalFormat.

Example:

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {

    NumberFormat nf1 = NumberFormat.getNumberInstance(Locale.ENGLISH);
    DecimalFormat df1 = (DecimalFormat)nf1;
    df1.applyPattern(pattern);
    String output = df1.format(value);
    System.out.println("Input: " + value + ", pattern: " + pattern + " output: " + output);


    NumberFormat nf2 = NumberFormat.getNumberInstance(Locale.GERMAN);
    DecimalFormat df2 = (DecimalFormat)nf2;
    df2.applyPattern(pattern);
    output = df2.format(value);
    System.out.println("Input: " + value + ", pattern: " + pattern + " output: " + output);

  }

  static public void main(String[] args) {
    customFormat("###,###.###", 123456.789);
   }
}

Output:

Input: 123456.789, pattern: ###,###.### output: 123,456.789
Input: 123456.789, pattern: ###,###.### output: 123.456,789

Upvotes: 3

Related Questions