How do I change DecimalFormat pattern?

To change the pattern use by the DecimalFormat when formatting a number we can use the DecimalFormat.applyPattern() method call. In this example we use three different patterns to format the given input number. The pattern determines what the formatted number looks like.

package org.kodejava.example.text;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class FormatterPattern {
    public static void main(String[] args) {
        String[] patterns = {
                "###,###,###.##",
                "000000000.00",
                "$###,###.##"
        };
        
        double before = 1234567.899;

        //
        // To obtain a NumberFormat for a specific locale,
        // including the default locale, call one of NumberFormat's
        // factory methods, such as getNumberInstance(). Then cast 
        // it into a DecimalFormat.
        //
        DecimalFormat format = (DecimalFormat) 
                NumberFormat.getNumberInstance(Locale.UK);
        for (String pattern : patterns) {
            //
            // Apply the given pattern to this Format object
            //
            format.applyPattern(pattern);

            //
            // Gets the formatted value
            //
            String after = format.format(before);

            System.out.println("input: " + before + "| pattern: " +
                    pattern + " | output: " + after);
        }
    }
}

The output of the program shown below:

input: 1234567.899| pattern: ###,###,###.## | output: 1,234,567.9
input: 1234567.899| pattern: 000000000.00 | output: 001234567.90
input: 1234567.899| pattern: $###,###.## | output: $1,234,567.9

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply