See Also: NumberFormat Members
The abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are.
NumberFormat helps you to format and parse numbers for any locale. Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.
To format a number for the current locale, use one of the factory class methods:
java Example
myString = NumberFormat.getInstance().format(myNumber);
If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
java Example
NumberFormat nf = NumberFormat.getInstance(); for (int i = 0; i < a.length; ++i) { output.println(nf.format(myNumber[i]) + "; "); }
To format a number for a different locale, specify it in the call to getInstance.
java Example
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
You can also use a NumberFormat to parse numbers:
java Example
myNumber = nf.parse(myString);
Use #getInstance or #getNumberInstance to get the default number format. Use NumberFormat.IntegerInstance to get an integer number format, NumberFormat.CurrencyInstance to get the currency number format, and NumberFormat.PercentInstance to get a format for displaying percentages.
You can also control the display of numbers with methods such as setMinimumFractionDigits. If you want even more control over the format or parsing, or want to give your users more control, you can try casting the NumberFormat you get from the factory methods to a DecimalFormat. This will work for the vast majority of locales; just remember to put it in a try block in case you encounter an unusual one.
NumberFormat is designed such that some controls work for formatting and others work for parsing. For example, setParseIntegerOnly only affects parsing: If set to true, "3456.78" is parsed as 3456 (and leaves the parse position just after '6'); if set to false, "3456.78" is parsed as 3456.78 (and leaves the parse position just after '8'). This is independent of formatting.
You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to:
Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
DecimalFormat is the concrete implementation of NumberFormat, and the NumberFormat API is essentially an abstraction of DecimalFormat's API. Refer to DecimalFormat for more information about this API.