Java 12 – Compact Number Formatting

  • Post author:
  • Post category:Java 12
  • Post comments:1 Comment
Java 12 - Compact Number Formatting

This topic is about Java 12 – Compact Number Formatting.

Java 12 introduces compact formatting where we can format long numbers for decimal, currency or percentages to short form or long form. For example 1000 to 1K. Folloiwng syntax shows the usage −

NumberFormat formatter = NumberFormat.getCompactNumberInstance(
   Locale.US, NumberFormat.Style.SHORT);
   System.out.println(formatter.format(1000)
);

Consider the following example −

ApiTester.java

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

public class APITester {
   public static void main(String[] args) {
      NumberFormat formatter = NumberFormat.getCompactNumberInstance(
         Locale.US, NumberFormat.Style.LONG);

      System.out.println(formatter.format(1000));
      System.out.println(formatter.format(1000000));

      formatter = NumberFormat.getCompactNumberInstance(
         Locale.US, NumberFormat.Style.SHORT);

      System.out.println(formatter.format(1000));
      System.out.println(formatter.format(1000000));
   }
}

Output

1 thousand
1 million
1K
1M

In this topic we learned about Java 12 – Compact Number Formatting. To know more, Click Here.

This Post Has One Comment

Leave a Reply