Java Compact Number Instance -How to format numbers in human readable format

Java 12 has introduced a nice feature to represent numbers in its human readable format depending on the country and locale. This helps in representing numbers in a manner that is more popular to the dialect used in the particular region. For example, In US, the number 1000 is typically represented as “1K”. Earlier programmers had to fall back on their own custom code to display such representations. This is no longer required in Jdk 12 and above thanks to the Compact Number Instance feature in NumberFormat class. Let us look at this with an example.

package com.stackrules.java;

import java.text.NumberFormat;
import java.util.Locale;

public class CompactNumberFormat {

    public static void main(String[] args) {
        System.out.println("Hello");

        NumberFormat fmt = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
        String result = fmt.format(1000);
        System.out.println(result);
    }
}

Above example represented 1000 as 1k with just a couple of lines of code. if we change the number to say, String result = fmt.format(1000000); This will result in out of “1M”.

The number format has provided multiple styles that can be used. Above example used the SHORT style ( NumberFormat.Style.SHORT). If we change the style to LONG, the output will be different. Let us express the same code in LONG format and see how it behaves.

package com.stackrules.java;

import java.text.NumberFormat;
import java.util.Locale;

public class CompactNumberFormat {

    public static void main(String[] args) {

        NumberFormat fmt = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
        NumberFormat longFmt = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG);
        String result = fmt.format(1000000);
        System.out.println(result);
        String longResult = longFmt.format(1000000);
        System.out.println(longResult);

    }
}

The output will be

1M
1 million

By using the appropriate locale, we can format based on the style in any particular country.If you want to format it based on Chinese style, use the locale as Locale.CHINA

Leave a Comment