Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java String.format: numbers with localization

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?

like image 547
wziska Avatar asked Dec 07 '12 13:12

wziska


People also ask

What is locale in string format?

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.

What is %s and %D in Java?

%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"

What is %s in Java?

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.

How do you NumberFormat in Java?

To format a number for the current Locale, use one of the factory class methods: myString = NumberFormat. getInstance(). format(myNumber);


1 Answers

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'.

like image 76
serg10 Avatar answered Sep 23 '22 02:09

serg10