
- 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
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements