简体   繁体   中英

Android multiple currency formatting

I've got a couple of currencies in an enum, like this:

public enum Currencies{USD, LVL, EUR;}

And then there is a list of entries (of a class Item), and every entry has a number (of type long) of one of the aforementioned currencies. Now I want to formate this number as efficiently as possible.

What I've done thus far, is create a function

public String getFormatedSum(){
    NumberFormat mCurrencyFormatter = NumberFormat.getCurrencyInstance();
    mCurrencyFormatter.setCurrency(Currency.getInstance(getCurrency().toString()));
    return mCurrencyFormatter.format(getSum()); 
}

where getCurrency() returns the currency as a string of the particular Item.

Now I know, that this works, but I also suspect, that there should be a better way to do this. I had thought of instantiating formatters in a map, and then retrieving the one I needed and formatting, but the NumberFormat class seems to be static.

Any tips, or am I doing this right?

Well first of all, your getCurrency method could perhaps (by lookup or directly return a Currency (maybe it already does).

The NumberFormat is not static, but there is a static factory method for creating an instance. You can save the instance in a Map :

Map<Currency, NumberFormat> formatters = new HashMap<>();
...

NumberFormat getCurrencyFormatter(Currency currency) {
    NumberFormat result = formatters.get(currency);
    if (result == null) {
        result = NumberFormat.getCurrencyInstance();
        result.setCurrency(currency);
        formatters.put(currency, result);
    }
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM