- Java 12 Tutorial
- Java 12 - Home
- Java 12 - Overview
- Java 12 - Environment Setup
- Java 12 - Switch Expressions
- Java 12 - File mismatch method
- Java 12 - Compact Number Formatting
- Java 12 - Teeing Collectors
- Java 12 - String methods
- Garbage Collection Enhancements
- Java 12 - Microbenchmark
- Java Tutorial
- Java 8 Tutorial
- Java 9 Tutorial
- Java 10 Tutorial
- Java 11 Tutorial
- Java 12 Useful Resources
- Java 12 - Quick Guide
- Java 12 - Useful Resources
- Java 12 - Discussion
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