java.lang.Object | +----java.text.Format | +----java.text.NumberFormat
public abstract class NumberFormat
extends Format
implements Cloneable
NumberFormat is 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:
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.
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.
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);You can also use a NumberFormat to parse numbers:
myNumber = nf.parse(myString);Use getInstance or getNumberInstance to get the normal number format. Use getCurrencyInstance to get the currency number format. And use getPercentInstance to get a format for displaying percentages. With this format, a fraction like 0.53 is displayed as 53%.
You can also control the display of numbers with such methods 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 DecimalNumberFormat. 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.
You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to: