DecimalFormat

DecimalFormat belongs to the packagejava.text is a concrete subclass of NumberFormat that formats decimal numbers into strings and parses strings back into decimal numbers. It allows you to customize the format of numbers, such as specifying the number of decimal places, grouping separators (like commas), prefixes (like currency symbols), etc.

Common Used Methods

Simple Program

import java.text.DecimalFormat;

public class SimpleDecimalFormatExample {
    public static void main(String[] args) {
        double number = 1234567.89123;

        DecimalFormat formatter = new DecimalFormat("#,###.00");

        String formatted = formatter.format(number);

        System.out.println("Original Number: " + number);
        System.out.println("Formatted Number: " + formatted);
    }
}
/*
Original Number: 1234567.89123
Formatted Number: 1,234,567.89
*/

Problem Statement

Paani and Mahesh are building a Bank Management System. One of the requirements is to generate account summaries where the account balance must be displayed in a specific financial format:

  • Rounded to two decimal places
  • Includes commas as thousand separators
  • Includes a currency symbol prefix (₹)

Design a module that takes an array of customer balances and formats each one using the DecimalFormat class.

import java.text.DecimalFormat;

public class BankBalanceFormatter {

    public static void main(String[] args) {
        double[] customerBalances = {
            1200.5, 9876543.876, 450.2, 35000, 789.4567
        };

        // Custom pattern with currency symbol
        DecimalFormat formatter = new DecimalFormat("₹#,##0.00");

        System.out.println("----- Bank Account Summaries -----");
        for (int i = 0; i < customerBalances.length; i++) {
            String formatted = formatter.format(customerBalances[i]);
            System.out.println("Customer " + (i + 1) + " Balance: " + formatted);
        }
    }
}
/*
----- Bank Account Summaries -----
Customer 1 Balance: ₹1,200.50
Customer 2 Balance: ₹9,876,543.88
Customer 3 Balance: ₹450.20
Customer 4 Balance: ₹35,000.00
Customer 5 Balance: ₹789.46
*/

The DecimalFormat class in Java is a powerful utility to handle the formatting of numerical data, especially when presenting numbers in a human-readable way. It is commonly used in financial, banking, and scientific applications where precision and clarity of numbers are crucial.

Scroll to Top