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 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?
locale which is the locale value to be applied on the this method. format which is the format according to which the String is to be formatted. args which is the number of arguments for the formatted string. It can be optional, i.e. no arguments or any number of arguments according to the format.
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
the %s is a 'format character', indicating "insert a string here". The extra parameters after the string in your two function calls are the values to fill into the format character placeholders: In the first example, %s will be replaced with the contents of the command variable.
To format a number for the current Locale, use one of the factory class methods: myString = NumberFormat. getInstance(). format(myNumber);
From the documentation, you have to:
,
' 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'.
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