NumberFormat is an abstract class used to format numbers into locale-specific strings and to parse formatted strings back into numbers. It supports multiple locales, making it ideal for internationalized Java applications. It:
- Displays numbers in a clear, user-friendly, and locale-aware format
- Easily formats currency and percentage values
- Simplifies handling of internationalization (i18n) requirements
- Safely parses formatted numeric strings back into numbers
Commonly Used Factory Methods
Since NumberFormat is abstract, instances are created using its factory methods:
| Method | Description |
|---|---|
| getInstance() | Returns NumberFormat for the default locale |
| getCurrencyInstance() | Formats numbers as currency |
| getPercentInstance() | Formats numbers as percentages |
| getInstance(Locale l) | Returns NumberFormat for the specified locale |
| format(long / double) | Converts a number to a locale-specific string |
Example: Formatting a Number
import java.text.NumberFormat;
public class GFG {
public static void main(String[] args) {
NumberFormat nf = NumberFormat.getInstance();
System.out.println(nf.format(1234567.89));
}
}
Output
1,234,567.89
Explanation:
- NumberFormat.getInstance() returns a NumberFormat object for the system’s default locale.
- nf.format(1234567.89) converts the numeric value into a locale-specific formatted string.
- The output includes appropriate grouping separators (such as commas) based on the locale.
Note: Output may vary by locale.
Parsing Numbers Using NumberFormat
The parse() method converts formatted strings back into numeric values.
import java.text.NumberFormat;
public class GFG {
public static void main(String[] args) throws Exception {
NumberFormat nf = NumberFormat.getInstance();
Number num = nf.parse("1,234");
System.out.println(num);
}
}
Output
1234
Explanation:
- NumberFormat.getInstance() creates a formatter configured for the default locale.
- nf.parse("1,234") converts the formatted string back into a numeric Number object.
- The parsed result removes locale-specific symbols and prints the actual numeric value (1234).
NumberFormat vs DecimalFormat
Feature | NumberFormat | DecimalFormat |
|---|---|---|
Type | Abstract class | Concrete subclass |
Locale Support | Yes | Yes |
Custom Patterns | Limited | Yes (supports patterns) |
Ease of Use | Simple | More control |