Introduction to Java DecimalFormat
The java DecimalFormat class is used to apply decimal formats that are user-defined, to apply java DecimalFormat we use the class java.text.DecimalFormat
. Sometimes the decimal patterns printed by float or decimal may seem unprofessional or may add unnecessary digits after the decimal, to avoid this situation we use DecimalFormat class.
This class is used to edit text, user can mold the resultant output in any way wanted.
Importing javaDecimalFormat class
To use Java DecimalFormat we import the class java.text.DecimalFormat.
How to declare a pattern
We create DecimalFormat object and pass it the required pattern, the decimal, string, or integer value that needs to be changed into that particular format calls the format function of the class DecimalFormat.
package javaDecimalFormat;
//import the java decimalformat class
import java.text.DecimalFormat;
public class DecimalFormatClass {
public static void main(String[] args) {
//initialise a string with the desired decimal format
String format = "#,###,###";
//an object of DecimalFormat is created and we passed the desired pattern string in the constructor call.
DecimalFormat DecimalFormatObject = new DecimalFormat(format);
//a double variable initialised to which we apply the format.
double checkDouble = 1234131;
//the output will show the answer with required pattern.
System.out.println("The output of the following format will be" + DecimalFormatObject.format(checkDouble));
}
}
Output of the following code will be
The output of the following format will be1,234,131.
As the output shows, the value given is in the format that we declared. Similarly, we can provide a certain decimal points count, if we want the answer to be precise and rounded off to our desired decimal points, we can use java DecimalFormat.
package javaDecimalFormat;
// import the java decimalformat class
import java.text.DecimalFormat;
public class DecimalFormatClass {
public static void main(String[] args) {
double checkDouble = 1234131.00 / 123222131.132;
System.out.println("the format of the above example will be " + checkDouble);
}
}
Output of the following code is
the format of the above example will be 0.010015497935820914
This output seems rough and has no format whatsoever, to fix this we can use decimal format.
package javaDecimalFormat;
// import the java class to implement decimal format
import java.text.DecimalFormat;
public class DecimalFormatClass {
public static void main(String[] args) {
// initialise a string with the desired decimal format
String format = "0.000";
// an object of DecimalFormat is created and we passed the desired pattern string in the constructor call.
DecimalFormat DecimalFormatObject = new DecimalFormat(format);
// a double variable initialised to which we apply the format.
double checkDouble = 1234131.00 / 123222131.132;
// the output will show the answer with required pattern.
System.out.println("the format of the above example will be " + DecimalFormatObject.format(checkDouble));
}
}
Output of the same code now will be
the format of the above example will be 0.010
The answer is rounded off to three decimal points.
By default java decimal format symbols are listed below:
Symbols | Representation |
---|---|
. | decimal |
, | grouping |
E | exponential |
; | differentiate formats |
% | percentage |
- | negative |
Declaring a Java DecimalFormat using ApplyPattern
We can use the applyPattern function to apply any pattern initialized. The apply pattern function is used to apply the format that we initialized, it applies to all of the code.
package javaDecimalFormat;
// import the java class to implement decimal format
import java.text.DecimalFormat;
public class DecimalFormatClass {
public static void main(String[] args) {
// initialise a string with the desired decimal format
String format = "#,###,###";
// an object of DecimalFormat is created and we passed the desired pattern string in the constructor call.
DecimalFormat DecimalFormatObject = new DecimalFormat(format);
// Apply the pattern
DecimalFormatObject.applyPattern(format);
// a double variable initialised to which we apply the format.
double checkDouble = 1234131;
// the output will show the answer with required pattern.
System.out.println(DecimalFormatObject.format(checkDouble));
}
}
How to set a locale decimal format using DecimalFormat.Locale
We can specify a locale for DecimalFormat.Locale
The Locale is used to specify the format locale, as to which locale should be used for the given format.
package javaDecimalFormat;
// import the java decimalformat class
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class DecimalFormatClass {
public static void main(String[] args) throws ParseException {
// declaring a locale object to specify the local
needed.initialised with french locale.
Locale localeInit = new Locale("fr", "UK");
// string to show the pattern
String pattern = "###.###";
// the decimalformat object formed in which the locale is passed.
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(localeInit);
// this method applies the pattern according to the string in which we specified pattern
decimalFormat.applyPattern(pattern);
String format = decimalFormat.format(532.42334332432);
System.out.println("The format of this specific number will be :" + format);
}
}
The output of the following code is
The format of this specific number will be :532,42
The French locale is given.
Group data using Grouping SizeÂ
Java DecimalFormat has a function setGroupingSize(int), which is used to declare grouping size in a format
package javaDecimalFormat;
// import the java decimalformat class
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class DecimalFormatClass {
public static void main(String[] args) throws ParseException {
// declaring a locale object to specify the local needed.initialised with french locale.
Locale localeInit = new Locale("fr", "UK");
// string to show the pattern
String pattern = "###.###";
// the decimalformat object formed in which the locale is passed.
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(localeInit);
// this method applies the pattern according to the string in which we specified pattern
decimalFormat.applyPattern(pattern);
String format = decimalFormat.format(532.42334332432);
System.out.println("the format of this specific number will be :" + format);
}
}
Output of the following code will be
the format of this specific number will be :53,24,2
Since the grouping size is set to 2 so a comma will be placed after every 2 digits.
Using different Decimal Format Symbols to format data
Another major functionality of java DecimalFormat is the decimalFormatSymbols
- setDecimalSeperator():Â This function sets any symbol to represent a decimal point.
- setGroupingSeperator():Â This functions sets any symbol to represent a grouping symbol.
- setCurrency():Â This function sets the number to any desired currency.
- setDigit():Â This function is used to represent the digit in a format.
- setExponentSeperator():Â This function is used to represent an exponent in a format.
- setInfinity():Â This function is used to represent infinity in a format.
- setNaN():Â This function is used to represent an error.
- setPercent():Â This function is used to represent percentage in a format.
- setZeroDigit():Â This function is used to represent a zero digit in a format.
Code Implementation of different Decimal Format Symbols
The following code shows implementation of all the functions mentioned above
package javaDecimalFormat;
// import the java decimalfromat class
import java.text.DecimalFormat;
// import java decimalformat symbols
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
// import currency
import java.util.Currency;
// import locale
import java.util.Locale;
public class DecimalFormatClass {
// main
public static void main(String[] args) throws ParseException {
// setting french locale
Locale localeInit = new Locale("fr", "UK");
// object for symbols
DecimalFormatSymbols decimalSymbol = new DecimalFormatSymbols(localeInit);
// the point where decimal occurs, @ will apear
decimalSymbol.setDecimalSeparator('@');
// the point where grouping seperator occurs, $ will
appear
decimalSymbol.setGroupingSeparator('$');
// set an exponent seperator as e
decimalSymbol.setExponentSeparator("e");
// set infinity as inf
decimalSymbol.setInfinity("inf");
// set digit is w
decimalSymbol.setDigit('w');
// setZero digit to a
decimalSymbol.setZeroDigit('a');
// set currency to canadian french.
decimalSymbol.setCurrency(Currency.getInstance(Locale.CANADA_FRENCH));
// setting pattern
String pattern = "#,##,###.00";
// make a decimal format instance
DecimalFormat decimalFormat = new DecimalFormat(pattern, decimalSymbol);
// set the grouping size to 2
decimalFormat.setGroupingSize(2);
// set number
String number = decimalFormat.format(342128.234221);
// output shows the currency set
System.out.println("The currency is : " + decimalFormat.getCurrency());
// number after all the formating
System.out.println("the number is " + number);
}
}
The output of the following code will be:
The currency is : CAD the number is 34$21$28@23
Practice code
Implement the following code on your editor i.e. Eclipse, IntelliJ, Netbeans, etc, and check its output but first dry run the code and then check its output
package javaDecimalFormat;
// import the java class to implement decimal format
import java.text.DecimalFormat;
// import java decimal format symbols
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
// import currency
import java.util.Currency;
// import locale
import java.util.Locale;
public class DecimalFormatClass {
// main
public static void main(String[] args) throws ParseException {
DecimalFormatSymbols decimalSymbol = new DecimalFormatSymbols(Locale.CHINESE);
decimalSymbol.setDecimalSeparator('-');
decimalSymbol.setGroupingSeparator('!');
decimalSymbol.setExponentSeparator("E");
decimalSymbol.setInfinity("infinity");
decimalSymbol.setDigit('1');
decimalSymbol.setCurrency(Currency.getInstance(Locale.CANADA_FRENCH));
String pattern = "###,##,###";
// make a decimal format instance
DecimalFormat decimalFormat = new DecimalFormat(pattern, decimalSymbol);
decimalFormat.setGroupingSize(4);
String number = decimalFormat.format(342128.234221);
// output shows the currency set
System.out.println("The currency is : " + decimalFormat.getCurrency());
// WRITE THE OUTPUT OF THE CODE
System.out.println("the number is " + number);
}
}
Summary
We have studied how java DecimalFormat allows users to create desirable format, everything can be set accordingly, separators like decimal grouping exponential can be represented by the users choice of symbol, the datatypes like double, float are rounded off to decimal points of choice. By applying formats.
Further Reading
For further reading check these links.
java decimalformat
customizing formats