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.
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);
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With