“DecimalFormat” is a subclass of the “NumberFormat” class that is used to format decimal numbers. This class can be used to parse and format numbers of multiple data types i.e., integer(43), fixed-point numbers(4.35), scientific notation(2.54E), percentages(23%), etc. Moreover, this class is not thread-safe which means that attention should be paid while sharing the same instance between threads.
Contents Overview
- What is the “DecimalFormat” Class in Java?
- Working of the “DecimalFormat” Class in Java
- “DecimalFormat” Special Pattern Characters
- How to Use the “setGroupingSize()” Method With the “DecimalFormat” Class in Java?
What is the “DecimalFormat” Class in Java?
The “java.text.DecimalFormat” class in Java is used to format a number using a specified formatting pattern. It provides a format to show the numbers of multiple data types differently.
“DecimalFormat()” Constructor Syntax
DecimalFormat()
It creates a DecimalFormat using the given symbols and patterns for the default FORMAT locale.
DecimalFormat(String pat, DecimalFormatSymbols sym)
It creates a DecimalFormat using the specified patterns(represented by “pat”) and symbols(represented by “sym”) for the default FORMAT locale.
Working of the “DecimalFormat” Class in Java
To format a number using this class, define a pattern which is a sequence of specific characters that act as a template to format the particular value.
“DecimalFormat” Special Pattern Characters
There are a total of 11 special pattern characters. Following are the most vital ones using which the formatting of numbers can be done efficiently:
Character | Functionality |
---|---|
# | Prints a digit if given, else prints nothing. |
. | Specify where to add the decimal separator. |
, | Specify where to add the grouping separator. |
0 | Prints a digit if given, otherwise prints 0. |
; | Separates the formats. |
% | Multiplies by 100 and shows the number as a percentage. |
X | Marks the character to be utilized in the number suffix or prefix. |
‘ | Specifies a quote around the special characters in suffix or prefix of the formatted number. |
Before moving to the examples, consider the following method used in the examples:
format(): This method gives a formatted string using the locale, a format string, and arguments.
Syntax
public static String format(Locale lc, String x, Object... args)
Syntax Explanation
- “lc” is the locale to apply on the “format()” method.
- “x” refers to the format of the final string.
- “args” specify the arguments for the format string.
Return Value
It gives a formatted string.
Example 1: Using the “DecimalFormat” Class in Java
This example uses the “DecimalFormat” class to print the integer values according to the used special pattern character:
package jbArticles;
import java.text.DecimalFormat;
public class Decimalformat {
public static void main(String[] args){
int val1 = 1683256223;
int val2 = 8923;
DecimalFormat formatValue = new DecimalFormat("#,###");
System.out.println("First Value -> " + formatValue.format(val1)); System.out.println("Second Value " + formatValue.format(val2));
}}
Code Explanation
- Import the “java.text.DecimalFormat” library to use the “DecimalFormat” class.
- Initialize the two integer values to be formatted via the discussed class.
- Create a DecimalFormat instance and specify the special pattern character “#” as the constructor argument to format the values accordingly.
- Lastly, apply the “format()” method to format both integers according to the pattern character.
Output
In this output, it can be seen that the integers are separated by the commas according to the special pattern character position.
However, to get a value in a different pattern, specify the special pattern character in the class accordingly:
Example 2: Using the “DecimalFormat” Class With the “float” and “double” Types in Java
In this example, the discussed class will be used with the “float” and “double” values to format these values using special pattern characters:
package jbArticles;
import java.text.DecimalFormat;
public class Decimalformat {
public static void main(String[] args){
float value1 = 3.14159F;
double value2 = 8220847.902;
DecimalFormat formatValue = new DecimalFormat("#,###.##");
System.out.println("Float Value -> " + formatValue.format(value1));
System.out.println("Double Value -> " + formatValue.format(value2));
}}
Code Explanation
- First, initialize the “float” and “double” values, respectively.
- After that, use the “DecimalFormat” class via its instance to format the values according to the particular special pattern multiple characters i.e., “#”, “,” and “.”.
- Lastly, use the “format()” method to format both values accordingly.
Note: The specified format i.e., “#,###.##” implies that the result cannot have more than two decimal places.
Output
In this output, the “float” value is restricted to “2” decimal places and the “double” value has only “1” decimal place because it is rounded.
Example 3: Using the “DecimalFormat” Class to Apply Multiple Formatting in Java
This example explains the scenario when the user needs to add/use multiple formats of the same value. This can be done using multiple special pattern characters and “DecimalFormat” instances:
package jbArticles;
import java.text.DecimalFormat;
public class Decimalformat {
public static void main(String[] args){
float value = 20102.5f;
DecimalFormat multipleFormat = new DecimalFormat("$#,#0.0000");
DecimalFormat singleFormat = new DecimalFormat("#,###");
float mult = value * 2.5f;
System.out.println("Multiple Formatting -> " +multipleFormat.format(mult));
System.out.println("Single Formatting -> " +singleFormat.format(mult * 100));
}}
Code Explanation
- First, initialize a float value.
- In the next step, create a “DecimalFormat” instance that uses multiple special pattern characters and create another instance that also uses pattern characters.
- After that, apply some calculations i.e., multiplication, format the value differently, and observe the result in both cases.
Output
Here, it can be seen that the float value is formatted differently in both cases.
Example 4: Using “DecimalFormat” Class For a Specific Locale
In this code, the discussed class can be used for a target locale:
package jbArticles;
import java.text.DecimalFormat;
import java.util.*;
import java.text.*;
public class Decimalformat {
public static void main(String[] args){
Locale specifyLocale = new Locale("en", "UK");
String format pattern = "###.##";
DecimalFormat formatValue = (DecimalFormat)NumberFormat.getNumberInstance(specifyLocale);
formatValue.applyPattern(formatpattern);
String res = formatValue.format(12345.123);
System.out.println(res);
}}
Code Explanation
- Import the given libraries to use the “DecimalFormat”, “Locale”, and “NumberFormat” classes.
- Use the “Locale” class to specify the locale based on which the value needs to be formatted.
- After that, specify the special pattern characters as a template for the values to format.
- Now, apply the combined “getNumberInstance()”, “applyPattern()” and “format()” methods to format the specified value according to the pattern characters and the specific locale.
- Note: The “getNumberInstance()” method gives a number format for the default format locale and the “applyPattern()” method sets/applies the specified pattern.
Output
To use a different Locale i.e., “France” in this case, follow the below demonstration:
Here, it can be seen that “.” is replaced by “,” based on the changed Locale.
How to Use the “setGroupingSize()” Method With the “DecimalFormat” Class in Java?
The “setGroupingSize()” is a built-in method of the “DecimalFormat” class that is used to set the grouping size(integers in each group) for the DecimalFormat instance. For instance, the grouping size of the value “1,683,256,223” is “3” and for “89,23”, the value is “2”.
Syntax
public void setGroupingSize(int size)
In this syntax, “size” is the size of a new group of integers to be set.
Example: Applying the “setGroupingSize()” Method With the “DecimalFormat” Class
The following example explains the working of the discussed method with the “DecimalFormat” class such that the values are formatted according to the specified size of the new group of integers:
package jbArticles;
import java.text.DecimalFormat;
public class Decimalformat {
public static void main(String[] args){
int val1 = 1683256223;
int val2 = 89234;
DecimalFormat formatValue = new DecimalFormat("#,###");
formatValue.setGroupingSize(4);
System.out.println("First Value -> " + formatValue.format(val1));
System.out.println("Second Value " + formatValue.format(val2));
}}
Code Explanation
- Likewise, recall the approaches for initializing the integers and specifying the specific character pattern based on which the values need to be formatted.
- Moving ahead, use the “setGroupingSize()” method to set the size of the group of integers that is to be returned after formatting.
- Finally, use the “format()” method to format both the values accordingly.
Output
Here, it can be observed that the values are formatted according to the set group size.
Conclusion
The “java.text.DecimalFormat” class in Java is used to format a number using a specified formatting pattern. These patterns can be “#”, “.”, “,”, “;” etc and can be applied to multiple data type values in a custom way. In addition to that, this class can also be used with “Locale” to format the values based on the specified locales accordingly.