Reputation: 42690
In most case, how can we justify, when shall we use
NumberFormat.getInstance();
When shall we use
new DecimalForamt(...);
Upvotes: 15
Views: 12780
Reputation: 43
I had the same issue concerning locale. You can create a DecimalFormat object for a US locale by instantiating a NumberFormat and then casting it to a DecimalFormat. This is what Oracle says:
The preceding example created a DecimalFormat object for the default Locale. If you want a DecimalFormat object for a nondefault Locale, you instantiate a NumberFormat and then cast it to DecimalFormat. Here's an example:
NumberFormat nf = NumberFormat.getNumberInstance(loc);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern(pattern);
String output = df.format(value);
System.out.println(pattern + " " + output + " " + loc.toString());
https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
Upvotes: 3
Reputation: 17601
NumberFormat.getInstance actually gets the formatter based on the locale and number style. It might actually return the DecimalFormat() object. "DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers" - From JDK javadocs
Upvotes: 2
Reputation: 45324
If you want to specify how your numbers are formatted, then you must use the DecimalFormat constructor. If you want "the way most numbers are represented in my current locale", then use the default instance of NumberFormat.
Upvotes: 8