English 中文(简体)
Java 12 - Compact Number Formatting
  • 时间:2024-12-22

Java 12 - Compact Number Formatting


Previous Page Next Page  

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;

pubpc class APITester {
   pubpc 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 milpon
1K
1M
Advertisements