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 table with multiple header in iText 8? - March 16, 2024
- How do I add Image to a Table in iText 8? - March 11, 2024
- How do I downgrade Android SDK emulator version? - February 12, 2024