Formatting Currencies in Foreign Locales in Java
Try using setCurrency on the instance returned by getCurrencyInstance(Locale.GERMANY)
Broken:
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.GERMANY);
System.out.println(format.format(23));
Output: 23,00 €
Fixed:
java.util.Currency usd = java.util.Currency.getInstance("USD");
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.GERMANY);
format.setCurrency(usd);
System.out.println(format.format(23));
Output: 23,00 USD
import java.util.*;
import java.text.*;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();
NumberFormat lp; //Local Payment
lp = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("US: " + lp.format(payment));
lp = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println("India: " + lp.format(payment));
lp = NumberFormat.getCurrencyInstance(Locale.CHINA);
System.out.println("China: " + lp.format(payment));
lp = NumberFormat.getCurrencyInstance(Locale.FRANCE);
System.out.println("France: " + lp.format(payment));
}
}
I would add to answer from les2 https://stackoverflow.com/a/7828512/1536382 that I believe the number of fraction digits is not taken from the currency, it must be set manually, otherwise if client (NumberFormat) has JAPAN locale and Currency is EURO or en_US, then the amount is displayed 'a la' Yen', without fraction digits, but this is not as expected since in euro decimals are relevant, also for Japanese ;-).
So les2 example could be improved adding format.setMaximumFractionDigits(usd.getDefaultFractionDigits());
, that in that particular case of the example is not relevant but it becomes relevant using a number with decimals and Locale.JAPAN as locale for NumberFormat.
java.util.Currency usd = java.util.Currency.getInstance("USD");
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(
java.util.Locale.JAPAN);
format.setCurrency(usd);
System.out.println(format.format(23.23));
format.setMaximumFractionDigits(usd.getDefaultFractionDigits());
System.out.println(format.format(23.23));
will output:
USD23
USD23.23
In NumberFormat code something similar is done for the initial/default currency of the format, calling method DecimalFormat#adjustForCurrencyDefaultFractionDigits. This operation is not done when the currency is changed afterwards with NumberFormat.setCurrency