Advanced Localization

Placeholders in localized strings can support a range of flexible formatting options besides the basic {0} etc. that inserts the string representation of whatever object is passed as argument.

This page provides an overview of the supported message formats. The MessageFormat Javadoc provides more details.

Numbers

If numbers are passed as argument, they are typically printed without localized formatting.

To add locale-specific formatting, use the number format pattern:

{0,number}          (1)
{0,number,integer}  (2)
{0,number,currency} (3)
{0,number,percent}  (4)
{0,number,0.###E0}  (5)
1 Show a localized number, for example 1,234.56 (en_US), 1.234,56 (de_DE), or 1'234.5 (de_CH)
2 Number rounded to the nearest integer, e.g. 1,235 (en_US) or 1.235 (de_DE)
3 Show as currency
4 Percentage, e.g. 0.12 could be formatted to 12%
5 Arbitrary pattern can be defined as third argument as described on the DecimalFormat Javadoc. This example defines scientific notation, so 1234 would be shown as 1.234E3.

Choice

This pattern is useful when the translation of a term depends on the value of a number. Example:

{0,choice,0#No projects were|1#A project was|2<{0,number,integer} projects were} found.

In this example, the output depends on the value of the first parameter (index 0):

  • If it’s zero, No projects were found is printed.

  • If it’s one, A project was found is printed.

  • If it’s two or more, N projects were found is printed, N being the localized representation of the parameter value.

This demonstrates that patterns can be nested, the localized number is nested inside the choice pattern.

Date and Time

Date and time patterns can be used to display Date instances appropriate for the user’s locale.

These either use the predefined date and time styles (short, medium, long, and full), or a custom format for the SimpleDateFormat class.

{0,date}            (1)
{0,date,short}
{0,date,medium}
{0,date,long}
{0,date,full}
{0,date,yyyy-mm-dd} (2)
{0,time}            (3)
{0,time,short}
{0,time,medium}
{0,time,long}
{0,time,full}
{0,time,HH:mm:ss}   (4)
1 Default (medium) date format
2 Custom date format, in this case a date like 2017-02-27
3 Default (medium) time format
4 Custom time format, in this case a time like 17:45:32

References