Java 12 紧凑格式化数字
Java 12引入了紧凑格式化,可以将长数字格式化为十进制、货币或百分比的短形式或长形式。例如将1000格式化为1K。以下语法显示了用法−
NumberFormat formatter = NumberFormat.getCompactNumberInstance(
Locale.US, NumberFormat.Style.SHORT);
System.out.println(formatter.format(1000)
);
考虑以下示例 −
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));
}
}
输出
1 thousand
1 million
1K
1M