CompactNumberFormat Short And Long Styles
Render large counts as 15K and 1M with the compact number formatter, switch to LONG style for spelled-out words, and parse the short forms back into numbers.
Code
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class ViewerCounts {
public static void main(String[] args) throws ParseException {
NumberFormat shortForm =
NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
// 1000 以下保持原样,往上走 K / M 档位
System.out.println("999 -> " + shortForm.format(999));
System.out.println("15000 -> " + shortForm.format(15000));
System.out.println("1234567 -> " + shortForm.format(1234567));
// LONG 风格把档位拼成完整单词
NumberFormat longForm =
NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG);
System.out.println("long -> " + longForm.format(1234567));
// 默认只留整数位;放开一位小数才能区分 1.5M 与 1M
NumberFormat withFraction =
NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
withFraction.setMaximumFractionDigits(1);
System.out.println("1.5M -> " + withFraction.format(1500000));
// parse 把短形态还原成数值
System.out.println("parsed -> " + shortForm.parse("2K"));
}
}How it works
CompactNumberFormat Short And Long Styles keeps everything in the class ViewerCounts.
Applying it
The demo output is labeled (999 ->, 15000 ->, 1234567 ->), so each printed line points back to the operation that produced it.
Statements that matter
NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG);
withFraction.setMaximumFractionDigits(1);
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.
FAQ
- What does CompactNumberFormat Short And Long Styles print when run?
- No setup needed: run the file and look for labeled lines like `999 ->`, `15000 ->`, `1234567 ->` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.