Does <f:convertNumber> use the right number separator when using patterns to format currency?

穿精又带淫゛_ 提交于 2019-11-26 21:42:34

问题


Suppose I have the following <f:convertNumber> to format a currency-type number:

<f:convertNumber type="currency" locale="#{userSession.locale}" pattern="$###,###.###" />

In English, a million would be 1,000,000 but in Germany, it should be 1.000.000. My question is: If I use the above pattern, will JSF be aware of the number format of the specified locale and automatically use the correct separator?

If not, I'd be very grateful if you could show me how I can format a currency number and at the same time specify the right number separator.


回答1:


It's important to know and understand that the <f:convertNumber> tag uses DecimalFormat under the covers. You can find all pattern characters in its javadoc.

It seems that you expected that the DecimalFormat pattern characters , and . are also actually used in the final format. This is untrue. It are really merely pattern characters (like as d, M, y, etc as used bySimpleDateFormat). Basically, the pattern character , tells DecimalFormat to print the "grouping separator" as specified by the given locale and, equivalently, the pattern character . tells DecimalFormat to print the "decimal separator" as specified by the given locale.

In effects, the actual character being printed depends on the given locale. For English locale (locale="en"), the "grouping separator" being printed is just coincidentally also ,, but for German locale (locale="de") the "grouping separator" being printed is indeed ..


Unrelated to the concrete problem, the type attribute of <f:convertNumber> has totally no effect if the pattern attribute is specified. The type attribtue is basically superfluous in this example and can safely be removed without any side effects.

If you remove the pattern attribute, then it'll actually be used and you'll see that the default pattern for a currency is being used, which is same as ¤#,##0.00 for English locale and ¤ #,##0.00 for German locale. Also note that the pattern character representing the currency symbol is not $, but ¤. The currency symbol can be set separately via currencySymbol attribute. So the correct approach for currencies would be:

<f:convertNumber type="currency" locale="#{userSession.locale}" currencySymbol="$" />

Again, see the DecimalFormat javadoc as linked before.



来源:https://stackoverflow.com/questions/19765009/does-fconvertnumber-use-the-right-number-separator-when-using-patterns-to-for

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