DecimalFormat ignores given pattern but uses Locale

烂漫一生 提交于 2019-12-11 04:15:41

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/43615577/decimalformat-ignores-given-pattern-but-uses-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!