Home > front end >  Java DecimalFormat issue - DecimalFormat("0.0") returns data with a comma as separator ins
Java DecimalFormat issue - DecimalFormat("0.0") returns data with a comma as separator ins

Time:12-07

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
    }
}

Hi all, 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.

Thanks in advance for your help, Space:

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

10,4

100,5

3000,3

CodePudding user response:

You can change the decimal format like in this post

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;

CodePudding user response:

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.

  • Related