Java 12 introduces compact formatting where we can format long numbers for decimal, currency or percentages to short form or long form. For example 3000 to 3K. Folloiwng syntax shows the usage −
NumberFormat formatter = NumberFormat.getCompactNumberInstance(
Locale.US, NumberFormat.Style.SHORT);
System.out.println(formatter.format(2000));
Consider the following program −
Java12NumberFormat.java
import java.text.NumberFormat;
import java.util.Locale;
public class Java12NumberFormat {
public static void main(String[] args) {
// 1. NumberFormat with short
NumberFormat formatter1 = NumberFormat.getCompactNumberInstance(
Locale.US, NumberFormat.Style.SHORT);
System.out.println(formatter1.format(3000));
System.out.println(formatter1.format(3000000));
// 2. NumberFormat with long
NumberFormat formatter = NumberFormat.getCompactNumberInstance(
Locale.US, NumberFormat.Style.LONG);
System.out.println(formatter.format(3000));
System.out.println(formatter.format(3000000));
}
}
Output:
Now run the Java8DateTime as follows −
C:\hitechpoints\workspace\java12-feature\src>java Java12NumberFormat.java
It should produce the following output −
3K
3M
3 thousand
3 million