0

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
czetsuya
  • 4,773
  • 13
  • 53
  • 99

1 Answers1

3

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Hi BalusC, thanks again for the reply. BigDecimalConverter is just our implementation of a bigdecimal faces converter. Anyway I got your response and I totally misunderstood it. I think I can move on now. – czetsuya May 23 '13 at 09:04
  • Why is this not being linked to from everywhere? I work with JSP pages and Struts, and I just discovered a thousand places in our code where we are not doing this properly, because the and tags often don't take this into account. – Shotgun Ninja Apr 01 '15 at 18:49