Reputation: 23
I am trying to format a currency based on the accept-language header, but I'm having a little trouble.
An English-US user will understand € 10,000,000.15 but not the suitable-for-Germany equivalent, € 10.000.000,15
On the other hand, "$23,123 looks" fine to an English-US user, but "$23,123.00" looks very strange. So does "JPY23,123.00". The latter is what I get using the following code:
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.US);
format.setCurrency(java.util.Currency.getInstance("JPY"));
Even more disturbing is the rounding that happens when I display USD in ja_JP. if I format 7.95, it just shows as "USD8" instead of "USD7.95"
Is there any simple way to avoid this? Is there a better library for formatting currencies? Should I just format it as a number for the locale (if the currency isn't the locale's default), and then prepend the currency code or symbol?
Upvotes: 2
Views: 1837
Reputation: 135992
By default 10000000.15 euro is printed as EUR10,000,000.15
for Locale.US and 10.000.000,15 €
for Locale.GERMANY and it seems correct.
But USD8
for $7.75 looks really weird even for Japan. But this can be fixed:
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
format.setCurrency(currency);
format.setMaximumFractionDigits(currency.getDefaultFractionDigits());
System.out.println(format.format(7.95));
it prints USD7.95
for JAPAN/USD and JPY8
for US/JPY
Upvotes: 3