How to use DecimalFormat in Java

In Java, the DecimalFormat class is used to format decimal numbers by specifying formatting patterns. The DecimalFormat class is a subclass of the NumberFormat class.

We can format a number up to n decimal places using the DecimalFormat class. To use DecimalFormat we have to create a DecimalFormat object. Then the format method is called and the number is passed as a parameter.

The syntax for creating DecimalFormat object

DecimalFormat df = new DecimalFormat(pattern);

Few Number format patterns are:

  • 0 - Displays integer. If the digit is insufficient then fills in 0.
  • # - Displays digit only if it is not zero, omits otherwise.
  • . - Decimal separator that separates the integer part and decimal part.
  • , - It is a grouping separator.
  • E - It formats a number using scientific notation. (E4 means 4 power of 10)
  • % - It multiplies the number by 100 and shows the formatted number with a percentage symbol.
  • - - It formats the number with a negative prefix.
  • ; - It is a format pattern separator.
  • ? - It multiplies the format number by 1000 and shows the formatted number as per mile.
  • X - It uses the character as a number prefix or suffix.
import java.text.DecimalFormat;
public class Example {
    public static void main(String args[])
        double x = 272.963745;
        double y = 87251903;
        DecimalFormat df = new DecimalFormat("0");
        System.out.println(df.format(x)); // displays integer part of x
        df = new DecimalFormat("0.00");
        System.out.println(df.format(x)); // displays one integer and 2 decimal
        df = new DecimalFormat("#");
        System.out.println(df.format(x)); // displays integer part of x
        df = new DecimalFormat("#.##%");
        //multiplies the number by 100 and takes 2 decimal places
        // Displays use scientific counting method and take five decimal place.
        df = new DecimalFormat("#.#####E0");
        df = new DecimalFormat(",###");
        System.out.println(df.format(y)); // each 3 integer is separated by commas

The output is

0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions