Java String.format: numbers with localization

Is it possible to localize numbers in String.format in the same way as NumberFormat.format?

I expected to just use

String.format(locale, "%d", number) 

but this does not return the same result as when using NumberFormat. For instance:

 String.format(Locale.GERMAN, "%d", 1234567890) 

gives: "1234567890", and

 NumberFormat.getNumberInstance(Locale.GERMAN).format(1234567890) 

gives: "1.234.567.890"

If this is not possible, then what is the recommended way to localize text, including numbers?

+6
source share
2 answers

In the documentation you need:

  • provide a locale (as you do in your example)
  • include flag ',' in show locale-specific grouping delimiters

Thus, your example will be as follows:

 String.format(Locale.GERMAN, "%,d", 1234567890) 

Note the optional flag ',' in front of 'd'.

+9
source

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}); 
+2
source

All Articles