问题
I have a formatted string which is equal to USD 20
I want to convert it into $20
.
How can I do it efficient? Should I do it with regular expression but since with change in locale the country ISOCode will also change.
回答1:
What You need is this
import java.util.Currency;
import java.util.Locale;
.
// create a currency for US locale
Locale locale = Locale.US;
Currency curr = Currency.getInstance(locale);
// get and print the symbol of the currency
StringBuilder symbol = new StringBuilder(curr.getSymbol(locale));
System.out.println("Currency symbol is = " + symbol);
and then just concatenate the Amount to the symbol.
In this case, if the Locale changes, you will need to change it only in locale object. The rest of the logic will be the same.
Hope this helps.
回答2:
I believe that this should work for you (this assumes that some String s
has been declared and initialized):
Currency localCurrForJVM = Currency.getInstance(Locale.getDefault());
String localCurrencySymbol = localCurrForJVM.getSymbol();
s = s.replaceAll("[^0-9.]", "");
//using regex to replace all non-numeric, non-decimal characters with ""
s = new StringBuilder(s).insert(0, localCurrencySymbol).toString();
//prepends the symbol to the StringBuilder, which replaces s
Some references:
public static Locale getDefault()
Gets the current value of the default locale for this instance of the Java Virtual Machine.
The Java Virtual Machine sets the default locale during startup based on the host environment. It is used by many locale-sensitive methods if no locale is explicitly specified. It can be changed using the setDefault method.
and:
public static Currency getInstance(Locale locale)
Returns the Currency instance for the country of the given locale. The language and variant components of the locale are ignored. The result may vary over time, as countries change their currencies. For example, for the original member countries of the European Monetary Union, the method returns the old national currencies until December 31, 2001, and the Euro from January 1, 2002, local time of the respective countries.
Parameters: locale - the locale for whose country a Currency instance is needed
Returns: the Currency instance for the country of the given locale, or null
来源:https://stackoverflow.com/questions/18104084/convert-three-letter-currency-designation-to-symbol-designation-ex-usd-20-to-2