How to use the DecimalFormat class in Java?

In Java, you can format numbers using the DecimalFormat class. Here are some common methods of using the DecimalFormat class.

  1. Instantiate a DecimalFormat object:
  2. Create a new Decimal Format object using the given pattern.
  3. The pattern is a string used to specify the format of the number.
  4. Format numbers:
  5. Format the number using the decimal format.
  6. The number is the digit to be formatted.
  7. Set the decimal places:
  8. df.setFractionDigits(minFractionDigits, maxFractionDigits);
  9. You can use these two methods to set the minimum and maximum number of decimal places.
  10. Enable thousand separators.
  11. Set the grouping to be used in the dataframe.
  12. This method will enable the use of thousands separators.

Here is a complete example:

import java.text.DecimalFormat;

public class DecimalFormatExample {
    public static void main(String[] args) {
        double number = 12345.6789;
        String pattern = "#,##0.00";

        DecimalFormat df = new DecimalFormat(pattern);
        String formattedNumber = df.format(number);

        System.out.println("Formatted Number: " + formattedNumber);
    }
}

The output results are:

Formatted Number: 12,345.68

In this example, the number 12345.6789 is formatted as a string “12,345.68” with a thousand separator and two decimal places.

bannerAds