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 build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023