I have a simple question:
How to get the pattern used to format a number using NumberFormat
created for a specific locale as shown below:
NumberFormat
is an interface so there can be multiple implementations.
public String getPattern(NumberFormat numberFormat) {
if(numberFormat instanceof java.text.DecimalFormat)
return ((java.text.DecimalFormat)numberFormat).toPattern();
if(numberFormat instanceof java.text.ChoiceFormat)
return ((java.text.ChoiceFormat)numberFormat).toPattern();
throw new IllegalArgumentException("Unknown NumberFormat implementation");
}
Please note that this will work today, but may break in the future when other implementations are added.
The subclasses DecimalFormat and ChoiceFormat have a method toPattern(), so you must check using instanceof and call toPattern()
String pattern = null;
if (numberFormat instanceof DecimalFormat) {
pattern = ((DecimalFormat)numberFormat).toPattern();
}
Consider DecimalFormat.toLocalizedPattern() too