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?

Answers


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;
}

Need Your Help

Parsley not using custom error container for radio button group

javascript spring-mvc parsley.js

I am using Parsley JavaScript validation library in a Spring MVC project. I am trying to validate a 'required' radio button group.

How to configure log4j in WebApp?

java-ee log4j

I want to use log4j in my webapplication. Even though i have added log4j.props in src directory, log4j is not finding it and prints everything in console. But in standalone java app, it is finding in