How do I change number format symbols?

You can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers. These symbols include the decimal separator which can be changed using the setDecimalSeparator(), the grouping separator which can be change using the setGroupingSeparator() method. You can also alter the minus sign, and the percent sign, among others.

package org.kodejava.example.text;

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

public class NumberFormatSymbol {
    public static void main(String[] args) {
        DecimalFormat formatter;
        String pattern = "###,###.##";
        double number = 123456.789;

        //
        // Create a DecimalFormatSymbols object for United States
        // locale.
        //
        DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);

        //
        // Create a format object with the given pattern without
        // change the locale dfs then format the given value.
        //
        formatter = new DecimalFormat(pattern);
        String before = formatter.format(number);

        //
        // Change the decimal separator and grouping separator symbol.
        //
        dfs.setDecimalSeparator(',');
        dfs.setGroupingSeparator('.');
        dfs.setMinusSign('-');
        dfs.setPercent('%');

        //
        // Create a format object with the given pattern and symbol
        // then format the given value.
        //
        formatter = new DecimalFormat(pattern, dfs);
        String after = formatter.format(number);

        System.out.println("before: " + before + " | after: " + after);
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply