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.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 the 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);
}
}
Latest posts by Wayan (see all)
- How do I add an object to the beginning of Stream? - February 7, 2025
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024