How to get the pattern of Number Format of a specific locale?

让人想犯罪 __ 提交于 2019-11-30 09:26:33

问题


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:

import java.util.Locale;

Locale aLocale = new Locale("fr","CA");
NumberFormat numberFormat=NumberFormat.getNumberInstance(aLocale);

Here I want to know the pattern used to format a number in French language and the country of Canada.

For e.g. :

a number 123456.7890 is converted into 123 456,789 after formatting it means pattern may be # ###,### for above mentioned locale.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/22513607/how-to-get-the-pattern-of-number-format-of-a-specific-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!