By default, a number is formatted using RoundingMode.HALF_EVEN. However, we can explicitly set the rounding mode via NumberFormat.setRoundingMode().
Trying to condense this information into a utility class named NumberFormatters can be achieved as follows:
public static String forLocale(Locale locale, double number) {
return format(locale, Style.SHORT, null, number);
}
public static String forLocaleStyle(
Locale locale, Style style, double number) {
return format(locale, style, null, number);
}
public static String forLocaleStyleRound(
Locale locale, Style style, RoundingMode mode, double number) {
return format(locale, style, mode, number);
}
private static String format(
Locale locale, Style style, RoundingMode mode, double number) {
if (locale == null || style == null) {
return String.valueOf(number); // or use a default format
}
NumberFormat nf = NumberFormat.getCompactNumberInstance(locale,
style);
if (mode != null) {
nf.setRoundingMode(mode);
}
return nf.format(number);
}
Now, let's format the numbers 1000, 1000000, and 1000000000 with the US locale, SHORT style, and default rounding mode:
// 1K
NumberFormatters.forLocaleStyle(Locale.US, Style.SHORT, 1_000);
// 1M
NumberFormatters.forLocaleStyle(Locale.US, Style.SHORT, 1_000_000);
// 1B
NumberFormatters.forLocaleStyle(Locale.US, Style.SHORT,
1_000_000_000);
We can do the same with the LONG style:
// 1thousand
NumberFormatters.forLocaleStyle(Locale.US, Style.LONG, 1_000);
// 1million
NumberFormatters.forLocaleStyle(Locale.US, Style.LONG, 1_000_000);
// 1billion
NumberFormatters.forLocaleStyle(Locale.US, Style.LONG, 1_000_000_000);
We can also use the ITALIAN locale and SHORT style:
// 1.000
NumberFormatters.forLocaleStyle(Locale.ITALIAN, Style.SHORT,
1_000);
// 1 Mln
NumberFormatters.forLocaleStyle(Locale.ITALIAN, Style.SHORT,
1_000_000);
// 1 Mld
NumberFormatters.forLocaleStyle(Locale.ITALIAN, Style.SHORT,
1_000_000_000);
Finally, we can also use the ITALIAN locale and LONG style:
// 1 mille
NumberFormatters.forLocaleStyle(Locale.ITALIAN, Style.LONG,
1_000);
// 1 milione
NumberFormatters.forLocaleStyle(Locale.ITALIAN, Style.LONG,
1_000_000);
// 1 miliardo
NumberFormatters.forLocaleStyle(Locale.ITALIAN, Style.LONG,
1_000_000_000);
Now, let's suppose that we have two numbers: 1200 and 1600.
From the rounding mode's perspective, they will be rounded to 1000 and 2000, respectively. The default rounding mode, HALF_EVEN, will round 1200 to 1000 and 1600 to 2000. But if we want 1200 to become 2000 and 1600 to become 1000, then we need to explicitly set up the rounding mode as follows:
// 2000 (2 thousand)
NumberFormatters.forLocaleStyleRound(
Locale.US, Style.LONG, RoundingMode.UP, 1_200);
// 1000 (1 thousand)
NumberFormatters.forLocaleStyleRound(
Locale.US, Style.LONG, RoundingMode.DOWN, 1_600);