Java CompactNumberFormat Class Example

1. Introduction

This blog post introduces the CompactNumberFormat class in Java. Introduced in Java 12 as part of the java.text package, CompactNumberFormat provides a way to format numbers in a human-friendly, compact form, commonly used for displaying large numbers in a more readable way.

Definition

CompactNumberFormat is a class in Java that formats numbers into compact forms based on locale-specific patterns. This is particularly useful for displaying large numbers (like thousands, millions, etc.) in a condensed, human-readable format.

2. Program Steps

1. Create a CompactNumberFormat instance for a specific locale.

2. Format different numerical values using this instance.

3. Display the formatted numbers.

3. Code Program

import java.text.CompactNumberFormat;
import java.util.Locale;

public class CompactNumberFormatExample {
    public static void main(String[] args) {
        // Creating a CompactNumberFormat instance for the US locale
        CompactNumberFormat cnf = CompactNumberFormat.getInstance(Locale.US, CompactNumberFormat.Style.SHORT);

        // Formatting various numbers
        var formattedNumber1 = cnf.format(1000);
        var formattedNumber2 = cnf.format(1500);
        var formattedNumber3 = cnf.format(1000000);

        // Displaying the formatted numbers
        System.out.println("Formatted 1000: " + formattedNumber1);
        System.out.println("Formatted 1500: " + formattedNumber2);
        System.out.println("Formatted 1000000: " + formattedNumber3);
    }
}

Output:

Formatted 1000: 1K
Formatted 1500: 1.5K
Formatted 1000000: 1M

Explanation:

1. A CompactNumberFormat instance is created for the US locale using CompactNumberFormat.getInstance. The Style.SHORT format is specified to get a concise representation of numbers.

2. The format method of CompactNumberFormat is used to format different numbers (1000, 1500, 1000000) into a compact form.

3. The output demonstrates the conversion of large numeric values into a more readable, compact format, like 1K for 1000, 1.5K for 1500, and 1M for 1000000.

4. This example shows how CompactNumberFormat simplifies the display of large numbers, making them more understandable in user interfaces and reports.


Comments