Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get NumberFormat instance from currency code?

Tags:

How can I get a NumberFormat (or DecimalFormat) instance corresponding to an ISO 4217 currency code (such as "EUR" or "USD") in order to format prices correctly?

Note 1: The problem I'm having is that the NumberFormat/DecimalFormat classes have a getCurrencyInstance(Locale locale) method but I can't figure out how to get to a Locale object from an ISO 4217 currency code.

Note 2: There is also a java.util.Currency class which has a getInstance(String currencyCode) method (returning the Currency instance for a given ISO 4217 currency code) but again I can't figure out how to get from a Currency object to a NumberFormat instance...

like image 379
Adil Hussain Avatar asked Mar 19 '12 20:03

Adil Hussain


People also ask

In which package is the class NumberFormat?

NumberFormat class is present in java. text package, and it is an abstract class. NumberFormat class implements Serializable, Cloneable.


2 Answers

I'm not sure I understood this correctly, but you could try something like:

public class CurrencyTest {     @Test     public void testGetNumberFormatForCurrencyCode()     {         NumberFormat format = NumberFormat.getInstance();         format.setMaximumFractionDigits(2);         Currency currency = Currency.getInstance("USD");         format.setCurrency(currency);          System.out.println(format.format(1234.23434));     }    } 

Output:

1,234.23 

Notice that I set the maximum amount of fractional digits separately, the NumberFormat.setCurrency doesn't touch the maximum amount of fractional digits:

Sets the currency used by this number format when formatting currency values. This does not update the minimum or maximum number of fraction digits used by the number format.

like image 160
esaj Avatar answered Sep 22 '22 06:09

esaj


Locale can be used both to get the standard currency for the Locale and to print any currency symbol properly in the locale you specify. These are two distinct operations, and not really related.

From the Java Internationalization tutorial, you first get an instance of the Currency using either the Locale or the ISO code. Then you can print the symbol using another Locale. So if you get the US Currency from the en_US Locale, and call getSymbol() it will print "$". But if you call getSymbol(Locale) with the British Locale, it will print "USD".

So if you don't care what your current user's locale is, and you just care about the currencies, then you can ignore the Locale in all cases.

If you care about representing the currency symbol correctly based on your current user, then you need to get the Locale of the user specific to the user's location.

like image 45
Spencer Kormos Avatar answered Sep 23 '22 06:09

Spencer Kormos