Java DecimalFormat Class

Formatting Decimal Numbers with Java DecimalFormat (java.text.DecimalFormat)

Table of Contents

When you need to format decimal numbers, such as taking three or two decimal places for a number, showing only the integer part of a number, etc. such scenarios can be tackled with java.text.DecimalFormatclass, which can help you to format numbers using your specified pattern.

The java.text.DecimalFormat class is used to format numbers using a user specified formatting. This concrete subclass of NumberFormat allows formatting decimal numbers’ String representation using predefined patterns. It has a variety of features designed to make it possible to parse and format numbers in any locale.

Let us look at some of the main features of this class explained with code snippets and samples.

Creating DecimalFormat Object

The DecimalFormat object can be created simply by using its default constructor as

DecimalFormat decimalFormat = new DecimalFormat();

However  if you need to format a number you can create a DecimalFormat instance by providing the pattern as string as shown below

String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
- Advertisement -

The pattern parameter passed as String to the DecimalFormat constructor is the number pattern according to which the numbers would be formatted.

Special Pattern Characters

Symbols Description
0 Indicates digit. If not present 0 will be still displayed.
# Indicates digit. If not present then nothing printed (omitted).
. Decimal separator which is used to separate integer part and decimal fraction part.
Format the number with a negative prefix.
, Marks grouping separator (e.g., thousand or hundreds separator).
E Separates mantissa and exponent in scientific notation (meaning power of 10).
; Separates positive and negative sub patterns.
% Multiply by 100 and show as percentage.
\u2030 Multiply by 1000 and show as per mille value.
¤ (\u00A4) Currency sign, replaced by currency symbol.
Used to quote special characters in a prefix or suffix.

Common Pattern Examples

Input Number Pattern Formatted Output
3.14159 #.##### 3.14159
3.14159 #.### 3.141
23.2 00.00 23.20
2.3323345 #.##% 233.23%
4.25 00.##0 04.250
233233.45 ###,###.##0 233,233.450

Formatting Numbers Using Pattern

The format() method of the DecimalFormat class is used to format the numbers into desired pattern. Here are the examples using format() method –

import java.text.DecimalFormat;

public class DecimalFormatter {

    public static void main(String[] args) {

        double dbNum = 170180.24523D;    // number to be formatted

        /* Basic Formatting Process */
        String strPattern = "######.#####";  // desired formatting pattern
        DecimalFormat decimalFormat = new DecimalFormat(strPattern);   // DecimalFormat
        String strFormattedNum = decimalFormat.format(dbNum);   // now format the number
        System.out.println(dbNum + " -> " + strFormattedNum);    // output = 170180.24523

        /* More Formatting Examples */
        strPattern = "######.###";  // To print full integer but only 3 decimal places
        decimalFormat = new DecimalFormat(strPattern);
        strFormattedNum = decimalFormat.format(dbNum);
        System.out.println(dbNum + " -> " + strFormattedNum);    // output = 170180.245

        strPattern = "######.000000";  // To print extra 0 in decimal value
        decimalFormat = new DecimalFormat(strPattern);
        strFormattedNum = decimalFormat.format(dbNum);
        System.out.println(dbNum + " -> " + strFormattedNum);    // output = 170180.245230

        strPattern = "#";  // To print only integer value part
        decimalFormat = new DecimalFormat(strPattern);
        strFormattedNum = decimalFormat.format(dbNum);
        System.out.println(dbNum + " -> " + strFormattedNum);    // output = 170180

        strPattern = "0000000.###";  // extra zero in integer part & 3 decimal places
        decimalFormat = new DecimalFormat(strPattern);
        strFormattedNum = decimalFormat.format(dbNum);
        System.out.println(dbNum + " -> " + strFormattedNum);    // output = 0170180.245

        strPattern = "#.##%";  // multiply by 100 and display as % with 3 decimal places
        decimalFormat = new DecimalFormat(strPattern);
        strFormattedNum = decimalFormat.format(dbNum);
        System.out.println(dbNum + " -> " + strFormattedNum);    // output = 17018024.52%
    }

}

The above code produces the following output:

170180.24523 -> 170180.24523
170180.24523 -> 170180.245
170180.24523 -> 170180.245230
170180.24523 -> 170180
170180.24523 -> 0170180.245
170180.24523 -> 17018024.52%

Creating DecimalFormat for Locale

You can also create DecimalFormat object for a specific Locale, other then the currently running JVM locale by creating a NumberFormat object and casting it into a DecimalFormat as shown in the below example.

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class DecimalFormatWithLocale {

    public static void main(String[] args) {

        double dbNum = 170180.24523D;
        NumberFormat nFormat = NumberFormat.getNumberInstance(Locale.GERMANY);
        DecimalFormat dFormat = (DecimalFormat) nFormat;   // cast NumberFormat
        String strFormattedNum = dFormat.format(dbNum);
        System.out.println(strFormattedNum + " - " + Locale.GERMANY.getDisplayName());
    }
}

As you can see from the output below, as per Germany locale, the output number is formatted with dot(.) as the 100s separator for integer part, while the fraction part uses the comma(,) as the separator.

170.180,245 - German (Germany)

DecimalFormat With Locale & Pattern

Here is another example of DecimaFormat for using both Locale as well as user specified pattern together while formatting a decimal number –

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class DecimalFormatPatternAndLocale2 {

    public static void main(String[] args) {

        double dbNum = 170180.24523D;
        String strPattern = "#.#####";

        NumberFormat nFormat = NumberFormat.getNumberInstance(Locale.GERMANY);
        DecimalFormat dFormat = (DecimalFormat) nFormat;    // cast NumberFormat

        String strFormattedNum = dFormat.format(dbNum);
        System.out.print("With GERMANY Locale = " + strFormattedNum + "\n");

        dFormat.applyPattern(strPattern);
        strFormattedNum = dFormat.format(dbNum);
        System.out.println("With Locale & Pattern = " + strFormattedNum);
    }
}

The above code produces the following output:

With GERMANY Locale = 170.180,245
With Locale & Pattern = 170180,24523

Grouping Integer Numbers

You can use setGroupingSize() method of DecimalFormat to change or set the number of digits you want to group in the integer part of the number. The below example demonstrates grouping integer part

You can also use setGroupingSize() along with pattern to specify format for both integer as well as decimal part of the number –

import java.text.DecimalFormat;

public class DecimalFormatGrouping {

    public static void main(String[] args) {

        double dbNum = 170180.24551D;
        DecimalFormat dFormat = new DecimalFormat();
        dFormat.setGroupingSize(4);

        String strFormattedNum = dFormat.format(dbNum);
        System.out.println(dbNum + " GroupSize(4) = " + strFormattedNum);

    }
}

The above code gives the following output:

170180.24551 GroupSize(4) = 17,0180.246

Using DecimalFormatSymbols for Pattern

The DecimalFormatSymbols class can also be used to change the decimal separator and the integer grouping separator characters. Here is an example using following methods of DecimalFormatSymbols class:

  • setDecimalSeparator()
  • setMonetaryDecimalSeparator()
  • setGroupingSeparator()
  • setCurrencySymbol()
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

public class DecimalFormatAndFormatSymbols {

    public static void main(String[] args) {

        double dbNum = 170180.24551D;
        String strPattern = "\u00A4#,###.###";

        DecimalFormatSymbols dFSymbols = new DecimalFormatSymbols();
        dFSymbols.setDecimalSeparator('-');
        dFSymbols.setMonetaryDecimalSeparator('-');
        dFSymbols.setGroupingSeparator(':');
        dFSymbols.setCurrencySymbol("$");

        DecimalFormat dFormat = new DecimalFormat(strPattern, dFSymbols);
        String strFormattedNum = dFormat.format(dbNum);

        System.out.println(strFormattedNum);
    }
}

The above code gives the following output:

$170:180-246

Rounding With DecimalFormat

The DecimalFormat class also comes handy with setRoundingMode() method for rounding the decimal numbers. Either you can create a separate instance of the RoundingMode class and pass as parameter to this method or you can directly pass the desired rounding mode using the static fields of RoundingMode class as shown in below example –

Input Number UP DOWN CEILING FLOOR HALF_UP HALF_DOWN HALF_EVEN
5.56565656
2.53232322
1.62121222
1.12121111
1.01111111
-1.0-1-1-1-1-1-1-1
-1.1-2-1-1-2-1-1-1
-1.6-2-1-1-2-2-2-2
-2.5-3-2-2-3-3-2-2
-5.5-6-5-5-6-6-5-6
Summary of Rounding Operations Under Different Rounding Modes
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class DecimalFormatRounding {

    public static void main(String[] args) {

        double dbNum = 170180.24551D;

        DecimalFormat dFormat = new DecimalFormat();
        dFormat.setRoundingMode(RoundingMode.HALF_UP);
        String strFormattedNum = dFormat.format(dbNum);
        System.out.println(dbNum + " Rounded-UP " + strFormattedNum);

        dFormat.setRoundingMode(RoundingMode.DOWN);
        strFormattedNum = dFormat.format(dbNum);
        System.out.println(dbNum + " Rounded-DOWN " + strFormattedNum);

    }
}

The above code gives the following output:

170180.24551 Rounded-UP 170,180.246
170180.24551 Rounded-DOWN 170,180.245

Setting Min/Max Fraction or Integer Digits

Probably one of the easiest way to set the minimum and maximum digits for both fraction as well as the Integer digits is by using the following methods provided in the DecimalFormat class as shown below –

  • setMaximumFractionDigits​(int newValue)
  • setMaximumIntegerDigits​(int newValue)
  • setMinimumFractionDigits​(int newValue)
  • setMinimumIntegerDigits​(int newValue)
import java.text.DecimalFormat;

public class DecimalFormatSetMinMaxDigit {

    public static void main(String[] args) {

        double dbNum = 170180.24551D;

        DecimalFormat deciFormat = new DecimalFormat();
        System.out.println("Original Num: " + dbNum);

        String strFormattedNum = deciFormat.format(dbNum);
        System.out.println("JVM Locale Formatted Num: " + strFormattedNum);

        String strPattern = "#,####.####";
        deciFormat.applyPattern(strPattern);
        strFormattedNum = deciFormat.format(dbNum);
        System.out.println("Pattern Formatted Num: " + strFormattedNum);

        deciFormat.setMinimumFractionDigits(1);
        deciFormat.setMaximumFractionDigits(4);
        strFormattedNum = deciFormat.format(dbNum);

        System.out.println("With Min/Max Fraction Digits: " + strFormattedNum);

        deciFormat.setMinimumIntegerDigits(1);
        deciFormat.setMaximumIntegerDigits(3);
        strFormattedNum = deciFormat.format(dbNum);

        System.out.println("With Min/Max Integer & Fraction Digits: " + strFormattedNum);

    }
}

The above code gives the following output:

Original Num: 170180.24551
JVM Locale Formatted Num: 170,180.246
Pattern Formatted Num: 17,0180.2455
With Min/Max Fraction Digits: 17,0180.2455
With Min/Max Integer & Fraction Digits: 180.2455

Specifying String Literals Within Pattern

Another feature of the DecimalFormat class pattern is that it allows you to specify your own custom string literals within your pattern. Here is an example –

import java.text.DecimalFormat;

public class DecimalFormatAndStringLiteral {

    public static void main(String[] args) {

        double dbNum = 170180.24551D;
        String strPattern = "My formatted number is #,###.###";

        DecimalFormat deciFormat = new DecimalFormat(strPattern);
        String strFormattedNum = deciFormat.format(dbNum);

        System.out.println(strFormattedNum);

    }
}

The above code produces the following output:

My formatted number is 170,180.246
Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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

JAVA CLASSES

Recent Posts

RELATED POSTS

Remove Duplicates from List Using Stream

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() method has been...

Convert String to java.time.LocalDate without Formatter

The LocalDate class has a parse method. You can use this to convert a String to a LocalDate. So, this code simply invokes the...

Remove Duplicates from List Using For-Loop

The simplest way to remove duplicates from a 'List' is to use a for-loop. The following code snippet demonstrates this method. First, the code creates...

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

Â

MORE ON CODEX

RECENT PROJECTS

Windows JDK Manager (win-jdk-Manager)

ADjo LABS PROJECT : Simple and lightweight desktop utility with Interactive cmd Interface for easy view, re-point and switching between JAVA versions on windows....

MORE IN THIS CATEGORY

Interpreted Vs Compiled Languages

This is based on an excerpt from one of my favourite literature on VBScript and in fact, is quite relevant with respect to one...

Convert List to Array Using ToArray Without Param

Java provides a toArray method on the 'List' interface. This can be used to convert a 'List' to an array. Since there are are...

Format Decimal Numbers Using Locale

If you want to create a DecimalFormat instance for a specific Locale, create a NumberFormat and cast it to a DecimalFormat. The java.text.DecimalFormat class is...

VBS Part 1 – Introduction and Background

At the upfront, this theoretical article might look boring to most of us but still, it is advisable to know about our scripting friend...

CHECKOUT TUTORIALS

Java Tutorial #5 – Loop Statements

Iteration statements are used to repeat a particular block of code until a certain condition is true. In this article, we will be taking...