39. Compact number formatting

Starting with JDK 12, a new class for compact number formatting was added. This class is named java.text.CompactNumberFormat. The main goal of this class is to extend the existing Java number formatting API with support for locale and compaction.

A number can be formatted into a short style (for example, 1000 becomes 1K) or into a long style (for example, 1000 becomes 1 thousand). These two styles were grouped in the Style enum as SHORT and LONG.

Besides the CompactNumberFormat constructor, CompactNumberFormat can be created via two static methods that are added to the NumberFormat class:

  • The first is a compact number format for the default locale with NumberFormat.Style.SHORT:
public static NumberFormat getCompactNumberInstance()
  • The second is a compact number format for the specified locale with NumberFormat.Style:
public static NumberFormat getCompactNumberInstance​(
Locale locale, NumberFormat.Style formatStyle)

Let's take a close look at formatting and parsing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.170.187