Formatting Double in Java [Examples]


The way decimals are displayed varies from location to location. Example: In Germany comma is used instead of a dot to represent a decimal. To format Double in Java, we can make use of DecimalFormat.

  • US: 123,456.789
  • France: 123 456,789
  • Germany: 123.456,789


Example 1: Using Locale
import java.text.DecimalFormat;
import java.util.Locale;

public class FormatDoubleExamples {

    public static void main(String... args) {
        Double doubleNumber = 40000.1234;

        DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.CANADA);
        System.out.println(decimalFormat.format(doubleNumber));

        decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMANY);
        System.out.println("GERMANY: "+ decimalFormat.format(doubleNumber));

        decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.FRANCE);
        System.out.println("FRANCE: "+ decimalFormat.format(doubleNumber));

        decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.JAPAN);
        System.out.println("JAPAN: "+ decimalFormat.format(doubleNumber));

    }
}
Output:
CANADA: 40,000.123
GERMANY: 40.000,123
FRANCE: 40 000,123
JAPAN: 40,000.123


Example 2: Using String.format
    public static void main(String... args) {
        Double doubleNumber = 40000.1234;
        System.out.println(String.format("%,.3f",doubleNumber));
        System.out.println(String.format(Locale.GERMAN,"%,.3f",doubleNumber));
    }
Output:
40,000.123
40.000,123


Example 3: Using hash (#) comma (,) and dot (.) patterns:
    public static void main(String... args) {
        Double myDouble = 12345.67890;

        DecimalFormatSymbols germany = new DecimalFormatSymbols(Locale.GERMANY);
        DecimalFormatSymbols us = new DecimalFormatSymbols(Locale.US);

        DecimalFormat decimalFormat1 = new DecimalFormat("#,###.###",germany);
        DecimalFormat decimalFormat2 = new DecimalFormat("#,###.###",us);

        System.out.println(decimalFormat1.format(myDouble));
        System.out.println(decimalFormat2.format(myDouble));
    }
Output:
12.345,679
12,345.679
Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap