DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Custom Compact Number Patterns With JDK 12 Compact Number Formatting

Custom Compact Number Patterns With JDK 12 Compact Number Formatting

There's are some new features worth checking out in JDK 12's compact number formatting.

Dustin Marx user avatar by
Dustin Marx
·
Jan. 29, 19 · News
Like (2)
Save
Tweet
Share
10.38K Views

Join the DZone community and get the full member experience.

Join For Free

The post "Compact Number Formatting Comes to JDK 12" has been the subject of discussion on a Java subreddit thread. Concerns expressed in that thread related to a presentation of the compact number formatting deal with digits of precision displayed and the compact number patterns displayed. The digits of precision can be addressed via use of CompactNumberFormat.setMinimumFractionDigits(int), and this approach is discussed in more detail in the post "Using Minimum Fractional Digits with JDK 12 Compact Number Formatting." The second issue (dislike for the compact patterns used in the pre-built CompactNumberFormat instances for certain languages) is addressed in this post.

As far as I can determine (and I certainly could be missing something), there's no method on CompactNumberFormat that allows for the compact number patterns to be set on an existing instance of CompactNumberFormat. However, if the constructor for CompactNumberFormat is used to obtain an instance of this class (rather than using one of the overloaded static factory methods on NumberFormat), then the compact number patterns can be supplied via that constructor to the new instance of CompactNumberFormat. This is demonstrated in the following code listing (which is also available on GitHub).

/** 
 * Provides an instance of {@code CompactNumberFormat} that has been 
 * custom created via that class's constructor and represents an 
 * alternate Germany German representation to that provided by an 
 * instance of {@code CompactNumberFormat} obtained via the static 
 * factory methods of {@code NumberFormat} for {@code Locale.GERMANY}. 
 * 
 * @return Instance of {@code CompactNumberFormat} with customized 
 *    alternate German compact pattern representations. 
 */  
private static CompactNumberFormat generateCustomizedGermanCompactNumberFormat()  
{  
   final String[] germanyGermanCompactPatterns  
      = {"", "", "", "0k", "00k", "000k", "0m", "00m", "000m", "0b", "00b", "000b", "0t", "00t", "000t"};  
   final DecimalFormat germanyGermanDecimalFormat  
      = acquireDecimalFormat(Locale.GERMANY);  
   final CompactNumberFormat customGermanCompactNumberFormat  
      = new CompactNumberFormat(  
         germanyGermanDecimalFormat.toPattern(),  
         germanyGermanDecimalFormat.getDecimalFormatSymbols(),  
         germanyGermanCompactPatterns);  
   return customGermanCompactNumberFormat;  
}  


There are three items worth special emphasis in the above code listing:

  1. The CompactNumberFormat(String, DecimalFormatSymbols, String[]) constructor allows for an array of Strings to be passed to the instance to specify the compact number patterns.
  2. The nature of the String[]-defining compact number patterns is defined in the Javadoc for CompactNumberFormat class, which states, "The compact number patterns are represented in a series of patterns where each pattern is used to format a range of numbers."
    • That same Javadoc provides a US locale-based example that provides these values for the range 100 to 1014 and it was that example that I adapted here.
    • More or fewer than 15 patterns can be supplied, but the first supplied pattern always corresponds to 100. The Javadoc states, "There can be any number of patterns and they are strictly index based starting from the range 100."
    • For demonstration purposes here, I adapted the patterns from an observation on the subreddit thread referenced earlier. I don't know much about German, but the argument for SI-based suffixes made a lot of sense and this is merely for illustrative purposes anyway.
  3. In this example, I retrieved the other two arguments to the CompactNumberFormat constructor from a JDK-provided instance of DecimalFormat for Germany German locale (Locale.GERMANY). This ensured that the decimal pattern and decimal format symbols of my custom Germany German instance of CompactNumberFormat would be the same as those associated with the JDK-provided instance.

The code listing above showed a call to a method called acquireDecimalFormat(Locale) to get a JDK-provided instance of DecimalFormat for Locale.GERMANY. For completeness, that method is shown next.

/** 
 * Provides an instance of {@code DecimalFormat} associated with 
 * the provided instance of {@code Locale}. 
 * 
 * @param locale Locale for which an instance of {@code DecimalFormat} 
 *    is desired. 
 * @return Instance of {@code DecimalFormat} corresponding to the 
 *    provided {@code Locale}. 
 * @throws ClassCastException Thrown if I'm unable to acquire a 
 *    {@code DecimalFormat} instance from the static factory method 
 *    on class {@code NumberFormat} (the approach recommended in the 
 *    class-level Javadoc for {@code DecimalFormat}). 
 */  
private static DecimalFormat acquireDecimalFormat(final Locale locale)  
{  
   final NumberFormat generalGermanyGermanFormat  
      = NumberFormat.getInstance(locale);  
   if (generalGermanyGermanFormat instanceof DecimalFormat)  
   {  
      return (DecimalFormat) generalGermanyGermanFormat;  
   }  
   throw new ClassCastException(  
        "Unable to acquire DecimalFormat in recommended manner;"  
      + " presented with NumberFormat type of '"  
      + generalGermanyGermanFormat.getClass().getSimpleName()  
      + "' instead.");  
}  


The code snippets shown above demonstrate how the compact number patterns can be customized for a given instance of CompactNumberFormat when the compact number patterns associated in instances of that class for a given Locale are not desirable. It'd be nice if there was a method on the CompactNumberFormat class to allow for overriding of some or all of the compact number patterns associated with an existing instance obtained via NumberFormat static factory class, but JDK 12 has entered ramp-down phase 2.

Java (programming language) Java Development Kit

Published at DZone with permission of Dustin Marx, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Mr. Over, the Engineer [Comic]
  • The Quest for REST
  • Load Balancing Pattern
  • How to Create a Real-Time Scalable Streaming App Using Apache NiFi, Apache Pulsar, and Apache Flink SQL

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: