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.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.printf("Input: %s, Pattern: %s, Output: %s%n",
before, pattern, 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
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023