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 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
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024