Thursday, March 1, 2012

How to format Decimal Number in Java - DecimalFormat Example

We often need to format decimal numbers in Java like formatting numbers upto 2 decimal places or 3 decimal places or we want to introduce leading zeros in front of numbers. Thankfully Java programming language provides many different ways to format numbers in Java like either using Math.round() or setScale() from BigDecimal but caveat is that they also do rounding of numbers i.e. 1.6 will be rounded on 2.0 if we use Match.round(). If we are just interested in formatting decimal numbers upto n decimal digits than DecimalFormat is way to go. java.text.DecimalFormat descends from NumberFormat and provides dynamic way of formatting numbers in Java. While creating instance of DecimalFormat you can pass an String pattern which describes on which format decimal number should be formatted and than DecimalFormat.format() method will do the rest for you. In this Java tutorial we will see how to format a decimal number in 2 decimal place, format upto 3 decimal place, using comma to separated 3 digits etc.

Java DecimalFormat Example

How to format Decimal Number in Java with ExampleDecimalFormat in Java is defined in java.text package and its a subclass of NumberFormat. In order to format a decimal number in Java we need an instance of DecimalFormat with predefined pattern. Once you have instance of DecimalFormat, you can call DecimalFormat.format() method for converting any double or long number into needed format. here is code example of creating DecimalFormat and formatting numbers in Java:

import java.text.DecimalFormat;

public class DecimalFormatExample {  
    public static void main(String args[])  {
        //formatting numbers upto 2 decimal places in Java
        DecimalFormat df = new DecimalFormat("#,###,##0.00");
        //formatting numbers upto 3 decimal places in Java
        df = new DecimalFormat("#,###,##0.000");


If you look at the output of decimal format example you will see that when we used format upto 2 decimal number any floating point number which has more than 2 digits after decimal point numbers will be printed only up to two digits. same is true in case of formatting numbers upto 3 decimal digit. if decimal number doesn't contain 3 digit than zero will be per pended.

Careful while Formatting Decimal number using DecimalFormat

Though java.text.DecimalFormat is a nice utility class and allow you to dynamically format numbers in Java it has one problem that its not thread-safe or synchronized properly. So never share decimal format between multiple threads. Its also not advisable to cache DecimalFormat as static resource without proper synchronization.

That's all on how to format a decimal number in Java using DecimalFormat. There are other way also like I said but DecimalFormat is neat, clean and simple way of formatting numbers upto n number of decimal places.

Further Reading
Java Fundamentals: The Java Language
SOLID Principles of Object Oriented Design
Head First Java

Other Java Tutorials you may like


Omi Tewary said...

I want to use decimal fromat concept in the folowing code.please help me with this
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class Sample3 {
public static void main(String args[]){
double amount,iRate,monPay,totalPay;
int years;
String amountStr;
String irateStr;
String yearsStr;
//takes input for loan amount,rate and loan period
amountStr = JOptionPane.showInputDialog(null,"Enter loan amount $ : ");
irateStr = JOptionPane.showInputDialog(null,"Enter % Annual Interest: ");
yearsStr = JOptionPane.showInputDialog(null,"Enter the loan Period; ");

amount = Double.parseDouble(amountStr); //convert input String into double
iRate = Double.parseDouble(irateStr); //convert input string into double
years = Integer.parseInt(yearsStr); //convert input string into integer

monPay = (amount * iRate / 1200) /
( 1 - Math.pow( 1 / ( 1 + iRate / 1200), 12 * years)) ;//calculate monthly payment
totalPay = monPay * 12 * years;

DecimalFormat df = new DecimalFormat("0.00");

JOptionPane.showMessageDialog(null,"your monthly payment is: " + monPay + "\n" +
"your total payment is: " + totalPay );


Anonymous said...

@omi tewary .In which format you want your ouput.

Post a Comment