views:

32

answers:

1

I know the way to get the Currency Object and other details for a currency in java using locale and NumberFormat class. But I am not able to find anything in the API to know whether currency symbol is display at start or end

E.g. 10 in US is $10 where $ is in the start of number) 10 in Zloty (polish currency) is 10 z (z to represent zloty symbol though actual symbol is different).

Is there any property in number format or currency class which can help me find whether currency symbol is placed in start or end?

+1  A: 

I don't seem to have very many Locales loaded... but france uses a trailing symbol, taiwan uses a leading symbol.

public class MyCurrency {
    public static void main(String[] args) {
        System.out.println(format(Locale.FRANCE, 1234.56f));
        System.out.println(format(Locale.TAIWAN, 1234.56f));
    }

    public static String format(Locale locale, Float value) {
        NumberFormat cfLocal = NumberFormat.getCurrencyInstance(locale);
        return cfLocal.format(value);
    }
}

Now if you really want to know if the currency symbol is at the beginning or the end, use the following as a starting point. Note the bPre variable...

public String format(Locale locale, Float value) {

    String sCurSymbol = "";
    boolean bPre = true;
    int ndx = 0;

    NumberFormat cfLocal = NumberFormat.getCurrencyInstance(locale);
    if (cfLocal instanceof DecimalFormat) { // determine if symbol is prefix or suffix
        DecimalFormatSymbols dfs =
                ((DecimalFormat) cfLocal).getDecimalFormatSymbols();
        sCurSymbol = dfs.getCurrencySymbol();
        String sLP = ((DecimalFormat) cfLocal).toLocalizedPattern();


        // here's how we tell where the symbol goes.
        ndx = sLP.indexOf('\u00A4');  // currency sign

        if (ndx > 0) {
            bPre = false;
        } else {
            bPre = true;
        }

        return cfLocal.format(value);

    }
    return "???";
}

Credit - I ripped the code from this page. http://www.jguru.com/faq/view.jsp?EID=137963

Tony Ennis
Thanks a lot for such a detailed answer and the link. Only question (might be naive) .. Is \u00A4 has special meaning. My case of conern right now is Polish Zloty currency and in general tomorrow may be something new. So I wanted to know if this magic string will handle all them.
Fazal
I think it's a formatting character. It has special meaning indeed - the one you want. It means, "put the currency symbol _here_"
Tony Ennis