Compact Number Formatting

A compact number formatter creates a textual representation that represents the compact form of a number. This formatter is an instance of the CompactNumberFormat that can be created by calling the getCompactNumberInstance() factory method of the NumberFormat class. For example, the value 1_000_000 can be formatted in a compact form as “1M” or “1 million”.

The compact form can be specified by the constants of the enum type Number-Format.Style, shown in Table 18.6. The compact form has a suffix, depending on the value of the number and the locale. Suffixes for the US locale are shown in Table 18.6. The compact form of numbers below 1000 is without any suffix.

Table 18.6 Compact Number Styles

Styles for compact number formVerbositySuffix for the US locale in compact form
NumberFormat.Style.SHORTShort number format style (default)T (Trillion), B (Billion), M (Million), K (Thousand) Examples: 2T, 2.5M, 1.5K
NumberFormat.Style.LONGLong number format styletrillion, billion, million, thousand Examples: 2 trillion, 2.5 million, 1.5 thousand

The code below creates two compact number formatters for the US locale that use the SHORT and the LONG compact number styles, respectively, to format numbers to their compact form.

Click here to view code image

NumberFormat shortCompactFormat = NumberFormat.getCompactNumberInstance(
    Locale.US, NumberFormat.Style.SHORT)
NumberFormat longCompactFormat = NumberFormat.getCompactNumberInstance(
    Locale.US, NumberFormat.Style.LONG);

The compact number formatters are used on different numerical values to create their compact form, as shown in Table 18.7.

Table 18.7 Formatting Numbers to Compact Form

Number nCompact form returned by shortCompactFormatter.format(n) methodCompact form returned by longCompactFormatter.format(n) method
9_400_000
9_500_000
12_500
12_510
999

“9M”
“10M”
“12K”
“13K”
“999”

“9 million”
“10 million”
“12 thousand”
“13 thousand”
“999”


9_400_000
9_500_000
12_500
12_510
999

(Max fraction digits = 2)

“9.4M”
“9.5M”
“12.5K”
“12.51K”
“999”

(Max fraction digits = 2)

“9.4 million”
“9.5 million”
“12.5 thousand”
“12.51 thousand”
“999”

Click here to view code image

System.out.println(shortCompactFormat.format(9_400_000));    // 9M
System.out.println(longCompactFormat.format(9_400_000));     // 9 million

The second row in Table 18.7 shows the compact form generated after the number of maximum fraction digits is set to 2 (p. 1122):

Click here to view code image

shortCompactFormat.setMaximumFractionDigits(2);
longCompactFormat.setMaximumFractionDigits(2);

Note the rounding that takes place depending on the value of the number. By default, RoundingMode.HALF_EVEN is used (see Table 18.9).

Leave a Reply

Your email address will not be published. Required fields are marked *