Java : CompactNumberFormat - API Examples

CompactNumberFormat (Java SE 18 & JDK 18) API Examples.
You will find code examples on most CompactNumberFormat methods.


Summary

CompactNumberFormat is a concrete subclass of NumberFormat that formats a decimal number in its compact form. The compact number formatting is designed for the environment where the space is limited, and the formatted string can be displayed in that limited space.

Class diagram

System.out.println(Locale.getDefault().toLanguageTag()); // en-US

final var number = 10000000;

final var format1 = NumberFormat.getCompactNumberInstance();
System.out.println(format1.getClass().getSimpleName()); // CompactNumberFormat
System.out.println(format1.format(number)); // 10M

final var format2 = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG);
System.out.println(format2.format(number)); // 10 million

final var format3 = NumberFormat.getCompactNumberInstance(Locale.JAPAN, NumberFormat.Style.SHORT);
System.out.println(format3.format(number)); // 1000万
final var format = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);

IntStream.range(0, 15).forEach(i -> {
    final var number = BigInteger.valueOf(10).pow(i);
    System.out.println(number + " : " + format.format(number));
});

// Result
// ↓
//1 : 1
//10 : 10
//100 : 100
//1000 : 1K
//10000 : 10K
//100000 : 100K
//1000000 : 1M
//10000000 : 10M
//100000000 : 100M
//1000000000 : 1B
//10000000000 : 10B
//100000000000 : 100B
//1000000000000 : 1T
//10000000000000 : 10T
//100000000000000 : 100T

Fields declared in NumberFormat

FRACTION_FIELD, INTEGER_FIELD

Please see the link below.

Constructors

CompactNumberFormat (String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns)

Creates a CompactNumberFormat using the given decimal pattern, decimal format symbols and compact patterns.

final String[] compactPatterns = {"", "", "", "0A", "00B", "000C"};
final var symbols = DecimalFormatSymbols.getInstance();

final var format = new CompactNumberFormat("000", symbols, compactPatterns);

System.out.println(format.format(1)); // 001
System.out.println(format.format(12)); // 012
System.out.println(format.format(123)); // 123
System.out.println(format.format(1234)); // 1A
System.out.println(format.format(12345)); // 12B
System.out.println(format.format(123456)); // 123C

CompactNumberFormat (String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns, String pluralRules)

Creates a CompactNumberFormat using the given decimal pattern, decimal format symbols, compact patterns, and plural rules.

Please see also : CompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns)

final String[] compactPatterns = {"{one:0x other:0y}", "{one:0xx other:0yy}"};
final var symbols = DecimalFormatSymbols.getInstance();

final var pluralRules = "one:i = 1 and v = 0";

final var format = new CompactNumberFormat("", symbols, compactPatterns, pluralRules);

System.out.println(format.format(1)); // 1x
System.out.println(format.format(2)); // 2y
System.out.println(format.format(10)); // 1xx
System.out.println(format.format(20)); // 2yy

Methods

CompactNumberFormat clone ()

Creates and returns a copy of this CompactNumberFormat instance.

final var symbols = DecimalFormatSymbols.getInstance();

final var format = new CompactNumberFormat("", symbols, new String[]{"0A", "00B", "000C"});
System.out.println(format.format(123)); // 123C

final var cloned = format.clone();

System.out.println(cloned.format(123)); // 123C
System.out.println(cloned.equals(format)); // true

boolean equals (Object obj)

Checks if this CompactNumberFormat is equal to the specified obj.

final var symbols = DecimalFormatSymbols.getInstance();

final var format1 = new CompactNumberFormat("", symbols, new String[]{"0A"});
final var format2 = new CompactNumberFormat("", symbols, new String[]{"0A"});
final var format3 = new CompactNumberFormat("", symbols, new String[]{"0B"});

System.out.println(format1.equals(format2)); // true
System.out.println(format1.equals(format3)); // false
System.out.println(format2.equals(format3)); // false

StringBuffer format (double number, StringBuffer result, FieldPosition fieldPosition)

Formats a double to produce a string representing its compact form.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    format.setMinimumFractionDigits(2);

    final var number = 12340.0;
    System.out.println(format.format(number)); // 12.34K

    {
        final var sb = new StringBuffer("num = ");
        System.out.println(sb); // num =

        final var pos = new FieldPosition(NumberFormat.INTEGER_FIELD);
        final var ret = format.format(number, sb, pos);
        System.out.println(ret); // num = 12.34K

        System.out.println(pos.getBeginIndex()); // 6
        System.out.println(pos.getEndIndex()); // 8
    }
    {
        final var sb = new StringBuffer("num = ");
        System.out.println(sb); // num =

        final var pos = new FieldPosition(NumberFormat.FRACTION_FIELD);
        final var ret = format.format(number, sb, pos);
        System.out.println(ret); // num = 12.34K

        System.out.println(pos.getBeginIndex()); // 9
        System.out.println(pos.getEndIndex()); // 11
    }
}

StringBuffer format (long number, StringBuffer result, FieldPosition fieldPosition)

Formats a long to produce a string representing its compact form.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    format.setMinimumFractionDigits(2);

    final var number = 12340L;
    System.out.println(format.format(number)); // 12.34K

    {
        final var sb = new StringBuffer("num = ");
        System.out.println(sb); // num =

        final var pos = new FieldPosition(NumberFormat.INTEGER_FIELD);
        final var ret = format.format(number, sb, pos);
        System.out.println(ret); // num = 12.34K

        System.out.println(pos.getBeginIndex()); // 6
        System.out.println(pos.getEndIndex()); // 8
    }
    {
        final var sb = new StringBuffer("num = ");
        System.out.println(sb); // num =

        final var pos = new FieldPosition(NumberFormat.FRACTION_FIELD);
        final var ret = format.format(number, sb, pos);
        System.out.println(ret); // num = 12.34K

        System.out.println(pos.getBeginIndex()); // 9
        System.out.println(pos.getEndIndex()); // 11
    }
}

final StringBuffer format (Object number, StringBuffer toAppendTo, FieldPosition fieldPosition)

Formats a number to produce a string representing its compact form.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    format.setMinimumFractionDigits(2);

    final var number = new BigInteger("12340000000000");
    System.out.println(format.format(number)); // 12.34T

    {
        final var sb = new StringBuffer("num = ");
        System.out.println(sb); // num =

        final var pos = new FieldPosition(NumberFormat.INTEGER_FIELD);
        final var ret = format.format(number, sb, pos);
        System.out.println(ret); // num = 12.34T

        System.out.println(pos.getBeginIndex()); // 6
        System.out.println(pos.getEndIndex()); // 8
    }
    {
        final var sb = new StringBuffer("num = ");
        System.out.println(sb); // num =

        final var pos = new FieldPosition(NumberFormat.FRACTION_FIELD);
        final var ret = format.format(number, sb, pos);
        System.out.println(ret); // num = 12.34T

        System.out.println(pos.getBeginIndex()); // 9
        System.out.println(pos.getEndIndex()); // 11
    }
}

AttributedCharacterIterator formatToCharacterIterator (Object obj)

Formats an Object producing an AttributedCharacterIterator.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    final var num = 123000;
    System.out.println(format.format(num)); // 123K

    final var it = format.formatToCharacterIterator(num);

    System.out.println("-- iterator --");
    for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
        System.out.println(c);
    }

    // Result
    // ↓
    //-- iterator --
    //1
    //2
    //3
    //K
}

int getGroupingSize ()

Returns the grouping size.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG)
        instanceof CompactNumberFormat format) {

    format.setGroupingUsed(true);

    final var num = 12345000000000000L;

    System.out.println(format.getGroupingSize()); // 0
    System.out.println(format.format(num)); // 12345 trillion

    format.setGroupingSize(3);

    System.out.println(format.getGroupingSize()); // 3
    System.out.println(format.format(num)); // 12,345 trillion
}

RoundingMode getRoundingMode ()

Gets the RoundingMode used in this CompactNumberFormat.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    System.out.println(format.getRoundingMode()); // HALF_EVEN

    System.out.println(format.format(1400)); // 1K
    System.out.println(format.format(1500)); // 2K
    System.out.println(format.format(1600)); // 2K

    format.setRoundingMode(RoundingMode.DOWN);
    System.out.println(format.getRoundingMode()); // DOWN

    System.out.println(format.format(1400)); // 1K
    System.out.println(format.format(1500)); // 1K
    System.out.println(format.format(1600)); // 1K
}

int hashCode ()

Returns the hash code for this CompactNumberFormat instance.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {
    System.out.println(format.hashCode()); // 580727548
}

if (NumberFormat.getCompactNumberInstance(Locale.JAPAN, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {
    System.out.println(format.hashCode()); // -2133385055
}

boolean isGroupingUsed ()

Returns true if grouping is used in this format.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG)
        instanceof CompactNumberFormat format) {

    final var num = 12345000000000000L;
    format.setGroupingSize(3);

    System.out.println(format.isGroupingUsed()); // false
    System.out.println(format.format(num)); // 12345 trillion

    format.setGroupingUsed(true);

    System.out.println(format.isGroupingUsed()); // true
    System.out.println(format.format(num)); // 12,345 trillion
}

boolean isParseBigDecimal ()

Returns whether the parse(String, ParsePosition) method returns BigDecimal.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    final var text = "12345678900000000000";

    System.out.println(format.isParseBigDecimal()); // false

    final var num1 = format.parse(text);
    System.out.println(num1); // 1.23456789E19
    System.out.println(num1.getClass().getSimpleName()); // Double

    format.setParseBigDecimal(true);
    System.out.println(format.isParseBigDecimal()); // true

    final var num2 = format.parse(text);
    System.out.println(num2); // 12345678900000000000
    System.out.println(num2.getClass().getSimpleName()); // BigDecimal
}

boolean isParseIntegerOnly ()

Returns true if this format parses only an integer from the number component of a compact number.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG)
        instanceof CompactNumberFormat format) {

    final var text = "1234.56 thousand";

    System.out.println(format.isParseIntegerOnly()); // false

    final var num1 = format.parse(text);
    System.out.println(num1); // 1234560
    System.out.println(num1.getClass().getSimpleName()); // Long

    format.setParseIntegerOnly(true);
    System.out.println(format.isParseIntegerOnly()); // true

    final var num2 = format.parse(text);
    System.out.println(num2); // 1234000
    System.out.println(num2.getClass().getSimpleName()); // Long
}

Number parse (String text, ParsePosition pos)

Parses a compact number from a string to produce a Number.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    final var text = "123K 456M";
    final var pos = new ParsePosition(0);

    final var ret1 = format.parse(text, pos);
    System.out.println(ret1); // 123000
    System.out.println(pos.getIndex()); // 4

    pos.setIndex(pos.getIndex() + 1);

    final var ret2 = format.parse(text, pos);
    System.out.println(ret2); // 456000000
    System.out.println(pos.getIndex()); // 9

    final var ret3 = format.parse(text, pos);
    System.out.println(ret3); // null
}

void setGroupingSize (int newValue)

Sets the grouping size.

Please see getGroupingSize().

void setGroupingUsed (boolean newValue)

Sets whether or not grouping will be used in this format.

Please see isGroupingUsed().

void setMaximumFractionDigits (int newValue)

Sets the maximum number of digits allowed in the fraction portion of a number.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    System.out.println(format.getMinimumFractionDigits()); // 0
    System.out.println(format.getMaximumFractionDigits()); // 0

    System.out.println(format.format(123000)); // 123K
    System.out.println(format.format(123450)); // 123K

    format.setMaximumFractionDigits(2);
    System.out.println(format.getMinimumFractionDigits()); // 0
    System.out.println(format.getMaximumFractionDigits()); // 2

    System.out.println(format.format(123000)); // 123K
    System.out.println(format.format(123450)); // 123.45K

    format.setMinimumFractionDigits(1);
    System.out.println(format.getMinimumFractionDigits()); // 1
    System.out.println(format.getMaximumFractionDigits()); // 2

    System.out.println(format.format(123000)); // 123.0K
    System.out.println(format.format(123450)); // 123.45K
}

void setMaximumIntegerDigits (int newValue)

Sets the maximum number of digits allowed in the integer portion of a number.

if (NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT)
        instanceof CompactNumberFormat format) {

    System.out.println(format.getMinimumIntegerDigits()); // 1
    System.out.println(format.getMaximumIntegerDigits()); // 309

    System.out.println(format.format(1234500000000000000L)); // 1234500T
    System.out.println(format.format(1000)); // 1K

    format.setMinimumIntegerDigits(3);
    format.setMaximumIntegerDigits(5);

    System.out.println(format.getMinimumIntegerDigits()); // 3
    System.out.println(format.getMaximumIntegerDigits()); // 5

    System.out.println(format.format(1234500000000000000L)); // 34500T
    System.out.println(format.format(1000)); // 001K
}

void setMinimumFractionDigits (int newValue)

Sets the minimum number of digits allowed in the fraction portion of a number.

Please see setMaximumFractionDigits(int newValue).

void setMinimumIntegerDigits (int newValue)

Sets the minimum number of digits allowed in the integer portion of a number.

Please see setMaximumIntegerDigits(int newValue).

void setParseBigDecimal (boolean newValue)

Sets whether the parse(String, ParsePosition) method returns BigDecimal.

Please see isParseBigDecimal().

void setParseIntegerOnly (boolean value)

Sets whether or not this format parses only an integer from the number component of a compact number.

Please see isParseIntegerOnly().

void setRoundingMode (RoundingMode roundingMode)

Sets the RoundingMode used in this CompactNumberFormat.

Please see getRoundingMode().

Methods declared in NumberFormat

format, format, getAvailableLocales, getCompactNumberInstance, getCompactNumberInstance, getCurrency, getCurrencyInstance, getCurrencyInstance, getInstance, getInstance, getIntegerInstance, getIntegerInstance, getMaximumFractionDigits, getMaximumIntegerDigits, getMinimumFractionDigits, getMinimumIntegerDigits, getNumberInstance, getNumberInstance, getPercentInstance, getPercentInstance, parse, parseObject, setCurrency

Please see the link below.

Methods declared in Format

format, parseObject

Please see the link below.


Related posts

Internationalization

Number

To top of page