Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I feed a ISO4217 Currency Code to a NumberFormat?

I want to avoid using Locale's and instead use currency codes (ISO 4217, like "USD"). I understand how to set a Currency class with the currency code, however, how could I incorporate this Currency into say a NumberFormat to format a double to said currency?

I understand both NumberFormat and Currency seperately, but how can I combined these to format doubles into real currency strings such as 4.00 -> $4.00? I must use NumberFormat, as I drop the decimal places to make whole currency figures such as $4 in this example.

Thank you for your help, Ryan

EDIT: Answer, .setCurrency, this is what I did not notice in NumberFormat, doh! I was too focused on constructing the NumberFormat with the Currency, but I was struggling as you can only construct from a Locale. Wish I thought of this earlier. Thanks! Next time I will read the method listing that much closer. I KNEW NumberFormat HAD to support a Currency class, it only made sense to use Currency in this fashion.

like image 641
AutoM8R Avatar asked Nov 01 '12 16:11

AutoM8R


2 Answers

This should let you display an amount in a given currency to the nearest whole unit of currency. I haven't tested it but think it's 95% right.

double amount = ...;
String currencyCode = ...;
Currency currency = Currency.getInstance(currencyCode);
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMaximumFractionDigits(0);
format.setCurrency(currency);
String formattedAmount = format.format(amount);
like image 168
Sean Owen Avatar answered Nov 10 '22 20:11

Sean Owen


Have you tried the following code:

    NumberFormat nf = NumberFormat.getCurrencyInstance();
    String currencyCode = "USD";
    nf.setCurrency(Currency.getInstance(currencyCode));
    double currencyAmmount = 4.00;
    String formattedValue= nf.format(currencyAmmount);

From the code above I got $4.00 and I assume this is what you expected.

I guess the most important thing here is to use NumberFormat.getCurrencyInstance() instead of NumberFormat.getInstance().

like image 29
vArDo Avatar answered Nov 10 '22 19:11

vArDo