Java DecimalFormat Example

We often need to format numbers, such as taking two decimal places for a number, show only the integer part of a number, etc. Java provides java.text.DecimalFormat class, which can help you to format numbers use your specified pattern as quickly as possible.

1. java.text.DecimalFormat Creation.

  1. DecimalFormat Constructor: The DecimalFormat constructor’s parameter is the format pattern that the numbers should be formatted with.
    String formatPattern = "###,###.###";
    
    DecimalFormat df = new DecimalFormat(formatPattern);
  2. applyPattern(String newPattern):  This method is used to change the number format pattern to a new pattern for the DecimalFormat instance. For example: decimalFormat.applyPattern(“#0.##”);
  3. applyLocalizedPattern(String newPattern): This method is similar to applyPattern(String newPattern), it also changes the number format pattern. The difference is that it will use localized characters in the pattern string instead of standard characters. For example, in Danish, the comma is used as the integer and fraction separator. But in English, a dot is used as that separator. So decimalFormat.applyLocalizedPattern(“#0,##”);  is used to format a number in the Danish language.

2. Number Formatting Pattern Syntax.

  1. Following characters can be used in number formatting patterns.
  2. 0: If the digit is insufficient then fill in 0. The digits will always be shown if it exists, otherwise, a 0 character will be shown.
  3. #: Show the digits only when it is not 0, otherwise omit.
  4. .: Decimal separator which is used to separate integer part and decimal fraction part.
  5. ,: This is a grouping separator. For example thousand separators.
  6. E: Formatting the number uses scientific notation. E5 means the five power of 10.
  7. %: Multiplies the format number by 100, shows the formatted number with a percentage.
  8. : Format the number with a negative prefix.
  9. ;: Format pattern separator.
  10. ?: Multiplies the format number by 1000, shows the formatted number with per mille.
  11. X: Use the character as a number prefix or suffix.
  12. ¤: This is the currency sign, which will be replaced by the locale currency sign.
  13. ¤¤: Format numbers use international monetary symbols.
  14. : The quote character around format number prefix or suffix.

3. java.text.DecimalFormat Example

  1. DecimalFormatExample.java
    package com.dev2qa.example.java;
    
    import java.text.DecimalFormat;
    
    public class DecimalFormatExample {
        public static void main(String args[])
        {
            // PI
            double pi=3.1415927;
    
            // Take one integer.
            DecimalFormat df = new DecimalFormat("0");
            System.out.println(df.format(pi)); // 3
    
            //Take one integer and two decimal
            df = new DecimalFormat("0.00");
            System.out.println(df.format(pi)); // 3.14
    
            // Take two integers and three decimals, and the inadequacies for integer are filled with 0.
            df = new DecimalFormat("00.000");
            System.out.println(df.format(pi));// 03.142
    
            // Take all the integers.
            df = new DecimalFormat("#");
            System.out.println(df.format(pi)); // 3
    
            // Count as a percentage and take two decimal places.
            df = new DecimalFormat("#.##%");
            System.out.println(df.format(pi)); //314.16%
    
            // light speed.
            long lightSpeed = 299792458;
    
            // Display use scientific counting method and take five decimal places.
            df = new DecimalFormat("#.#####E0");
            System.out.println(df.format(lightSpeed)); //2.99792E8
    
            // Use scientific counting method to show two integers and four decimal places.
            df = new DecimalFormat("00.####E0");
            System.out.println(df.format(lightSpeed)); //29.9792E7
    
            //Each three integer are separated by commas.
            df = new DecimalFormat(",###");
            System.out.println(df.format(lightSpeed)); //299,792,458
    
            //Embed formatting in text.
            df = new DecimalFormat("The speed of light is ,### meters per second.");
            System.out.println(df.format(lightSpeed));
        }
    }
  2. Below is the above source code execution output.
    3
    3.14
    03.142
    3
    314.16%
    2.99792E8
    29.9792E7
    299,792,458
    The speed of light is 299,792,498 meters per second

4. Special Locale DecimalFormat Instance Creation.

  1. If you want to create a DecimalFormat object for a special locale, not for the JVM default locale. You can use the below code.
    // Create special Locale DecimalFormat instance.
    Locale specialLocale  = new Locale("fr", "FR");
    String formatPattern = "###.##";
    
    DecimalFormat df1 = (DecimalFormat) NumberFormat.getNumberInstance(specialLocale);
    df1.applyPattern(formatPattern);
    
    String format = df1.format(123456789.123);
    System.out.println(format);
  2. The output of the above example code.
    123456789,12

5. java.text.DecimalFormatSymbols

  1. DecimalFormatSymbols class can be used to change the decimal separator, grouping separator character.
    // Use DecimalFormatSymbols to change decimal separators.
    Locale specialLocale1 = new Locale("fr", "FR");
    DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(specialLocale1);
    decimalFormatSymbols.setDecimalSeparator(';');
    decimalFormatSymbols.setGroupingSeparator(':');
    
    String formatPattern1 = "#,##0.###";
    DecimalFormat df2 = new DecimalFormat(formatPattern1, decimalFormatSymbols);
    
    String number = df2.format(123456789.1234567);
    System.out.println(number);
  2. The output should be as below, you can refer to java.text.DecimalFormatSymbols to see full methods introduction.
    123:456:789;123

6. Grouping Digits

  1. You can use DecimalFormat‘s setGroupingSize() method to change the default group digits number as you need.
  2. The default group digits number is 3. Below is an example.
    String formatPattern2 = "#,###.###";
    DecimalFormat df3 = new DecimalFormat(formatPattern2);
    df3.setGroupingSize(4);
    
    String number1 = df3.format(123456789.123);
    System.out.println(number1);
  3. The above example source code execution output is as below.
    1,2345,6789.123
  4. But you can also use the below number format pattern to achieve the same effect.
    String formatPattern = "####,####.###";

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.