Search code examples
javalocalestring-formattingdecimalformat

DecimalSeparator issue with String.Format()


Please find my code below:

double value = (double)-16325.62015;
System.out.println(String.format("%s", value));//-16325.62015
System.out.println(String.format(new Locale("de", "DE"), "%s", value));//-16325.62015
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(new Locale("de", "DE"));
System.out.println(dfs.getDecimalSeparator());//,

In the above code, Im getting the wrong decimal separator for German locale.

I have tried the below code also but it produces -16325,6

double value = (double)-16325.62015;
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(new Locale("de", "DE"));
DecimalFormat df = new DecimalFormat("#.#", dfs ); 
System.out.println(df.format(value));

is there any alternative way to print the output as -16325,62015

Note: I want to print double value with n number of decimal places for any specific locale

Thanks in advance


Solution

  • You must use %f not %s. When %s is used, Java converts your value to String using String.valueOf which uses the default locale.

    double value = (double)-16325.62015;
    System.out.println(String.format("%f", value));
    System.out.println(String.format(Locale.GERMANY, "%f", value));