DecimalFormat is being overridden by server settings

白昼怎懂夜的黑 提交于 2019-12-02 16:37:57

问题


Currently I'm having a problem displaying formatted decimals. In my local machine I have a decimal value: 0.002100000000 stored in database.

<h:outputText value="0.002100000000" converter="#{bigDecimal4DigitsConverter}" />

@FacesConverter("bigDecimal4DigitsConverter")
public class BigDecimal4DigitsConverter extends BigDecimalConverter {

    private DecimalFormat format = new DecimalFormat("#,##0.0000");

    @Override
    protected DecimalFormat getDecimalFormat() {
        return format;
    }
}

My problem is on my local machine it displays: 0.0021 - US Settings But in another server 0,0021 - French Settings

Why is that? I thought DecimalFormat, formats a decimal value regardless of locale?


回答1:


The DecimalFormat pattern is, as its name (and javadoc) says, a pure pattern. In this pattern, the , represents the grouping separator and the . represents the decimal separator. It's exactly like as that MMM represents the abbreviated month in SimpleDateFormat (note that it doesn't return MMM as month during formatting, but just like May or e.g. Mei depending on the locale).

The actual character being used as grouping separator and decimal separator (and the actual text being used as abbreviated month) during formatting depends on the locale, exactly as you observed. This is correct behavior. When you don't explicitly specify the locale during creating the DecimalFormat (or SimpleDateFormat), then the default locale as available by Locale#getDefault() will be assumed. You should actually be specifying the UIViewRoot#getLocale() or maybe a fixed locale like Locale.ENGLISH if your JSF web application is not localized for some unclear reason.

Please also note that DecimalFormat is (like SimpleDateFormat) not threadsafe (check the "Synchronization" section in the javadoc). You should not be creating it in class/instance scope, but in thread local scope (i.e. in the very same method block as where you need it).

I have only no idea which BigDecimalConverter you're using, the standard JSF one doesn't have a getDecimalFormat() method, so I can't give a more concrete example of the proper approach.



来源:https://stackoverflow.com/questions/16687407/decimalformat-is-being-overridden-by-server-settings

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