DecimalFormat 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");
        System.out.println(df.format(364565.14));
        System.out.println(df.format(364565.1454));
   
        //formatting numbers upto 3 decimal places in Java
        df = new DecimalFormat("#,###,##0.000");
        System.out.println(df.format(364565.14));
        System.out.println(df.format(364565.1454));
    }
   
}

Output:
364,565.14
364,565.15
364,565.140
364,565.145

 
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.


0 comments :

Post a Comment

 
Top