0
import java.text.DecimalFormat;

public class FormatTest {
     public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0.0");

        System.out.println(df.format(10.4));  // prints 10,4 instead of 10.4
        System.out.println(df.format(100.5)); // prints 100,5 instead of 100.5
        System.out.println(df.format(3000.3));// prints 3000,3 instead of 3000.3
    }
}

The output of my code above is below with a comma as decimal separator while normally it should be with a point. I use NetBeans 12.5 with Maven.

It seems like Java uses my local decimal separator instead of point. Also, I need to force point (".") as the only separator.

--- exec-maven-plugin:3.0.0:exec (default-cli) @ FormatTest ---

10,4

100,5

3000,3
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Space
  • 880
  • 3
  • 11
  • 22

2 Answers2

3

You can (and you actually need to avoid localization) actively configure the DecimalFormat with more detail as follows:

public class Main {
    public static void main(String[] args) throws Exception {
        DecimalFormat df = new DecimalFormat("0.0");
        DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
        decimalFormatSymbols.setDecimalSeparator('.');
        df.setDecimalFormatSymbols(decimalFormatSymbols);
        
        System.out.println(df.format(10.4));  // prints 10,4 instead of 10.4
        System.out.println(df.format(100.5)); // prints 100,5 instead of 100.5
        System.out.println(df.format(3000.3));// prints 3000,3 instead of 3000.3
    }
}

You can read more details in the reference documentation, where an important snippet can be read:

Special Pattern Characters

(...)

The characters listed here are used in non-localized patterns. Localized patterns use the corresponding characters taken from this formatter's DecimalFormatSymbols object instead, and these characters lose their special status.

João Dias
  • 16,277
  • 6
  • 33
  • 45
0

You can change the decimal format like in this post

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
Enrico
  • 415
  • 1
  • 10
  • In fact, in my code I use a solution on the same link, using .replace(',', '.') but I thought one could have something better (but equally short using DecimalFormat). – Space Dec 06 '21 at 19:52