Search

Dark theme | Light theme

March 1, 2021

Java Joy: Format Numbers In Compact Form

Since Java 12 we can format numbers in a compact style with the CompactNumberFormat class in the java.text package. A number like 23000 is formatted as 23K for the English locale. Instead of the short representation of K for 1000 we can also use a longer style where K is transformed as thousand for the English locale. We can use the same class to parse a String value that is in the compact style into a number.

In the following example we use several options of the CompactNumberFormat class:

package mrhaki.text;

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

public class CompactNumberFormat {

    public static void main(String[] args) throws ParseException {
        // When we would use NumberFormat.getCompactNumberInstance() the default system Locale
        // is used with the short style.
        // Create formatter for UK Locale and short style. 
        NumberFormat nf = NumberFormat.getCompactNumberInstance(Locale.UK, NumberFormat.Style.SHORT);
        assert "23K".equals(nf.format(23_000));
        assert "23K".equals(nf.format(23_491));
        assert "24K".equals(nf.format(23_791));
        assert "4M".equals(nf.format(4_250_392));

        nf.setMinimumFractionDigits(1);
        assert "4.3M".equals(nf.format(4_250_392));

        nf.setMaximumFractionDigits(3);
        assert "4.25M".equals(nf.format(4_250_392));

        // We can also parse the String value back to a number.
        assert Long.valueOf(23491).equals(nf.parse("23.491K"));

        // Instead of a short style we can also use a long style.
        nf = NumberFormat.getCompactNumberInstance(Locale.UK, NumberFormat.Style.LONG);
        assert "23 thousand".equals(nf.format(23_000));
        assert "4 million".equals(nf.format(4_250_392));

        // We can specify the minimum fraction digits to be used in the formatted number.
        nf.setMinimumFractionDigits(1);
        assert "4.3 million".equals(nf.format(4_250_392));

        // And the maximum fraction digits to change the ouput.
        nf.setMaximumFractionDigits(3);
        assert "4.25 million".equals(nf.format(4_250_392));
        
        // If we would use another locale we can see the output will be changed
        // if applicable.
        Locale dutch = new Locale("nl", "NL");
        nf = NumberFormat.getCompactNumberInstance(dutch, NumberFormat.Style.SHORT);
        assert "23K".equals(nf.format(23_230));

        nf = NumberFormat.getCompactNumberInstance(dutch, NumberFormat.Style.LONG);
        assert "23 duizend".equals(nf.format(23_230));
    }
}

Written with Java 15.