问题
Is it possible to localize numbers in String.format call the same way as NumberFormat.format does?
I've expected it simply to use
String.format(locale, "%d", number)
but this doesn't return the same result as if using NumberFormat. For example:
String.format(Locale.GERMAN, "%d", 1234567890)
gives: "1234567890", while
NumberFormat.getNumberInstance(Locale.GERMAN).format(1234567890)
gives: "1.234.567.890"
If it can't be done, what's recommended way for localizing text including numbers?
回答1:
From the documentation, you have to:
- supply a locale (as you are doing in your example)
- include the ',' flag to show locale-specific grouping separators
So your example would become:
String.format(Locale.GERMAN, "%,d", 1234567890)
Note the additional ',' flag before the 'd'.
回答2:
An alternative to String.format()
is to use MessageFormat:
MessageFormat format = new MessageFormat("The number is {0, number}", Locale.GERMAN);
String s = format.format(new Object[] {number});
来源:https://stackoverflow.com/questions/13763700/java-string-format-numbers-with-localization