Using MessageFormat
Home ] Up ] Using NumberFormat ] Using DecimalFormat ] DecimalFormat Example ] [ Using MessageFormat ]

 

 

However, for most purposes, you can use MessageFormat to format numbers:

 package inputOutput;
 
 import java.text.MessageFormat;
 
 public class FormatNumber
 {
    public static void main(String[] args)
    {
        Customer[] cust = 
        {
            new Customer(1, "Heather Gilmartin", 200.00),
            new Customer(2, "Bill Gates", -3000000.00),
            new Customer(500, "Crocodile Dundee", 1000.00)
        };
        for (int i = 0; i < cust.length; i++)
        {
            printCustomerStatus(cust[i]);
        }
    }
    
    static void printCustomerStatus(Customer cust)
    {
        String pattern = 
            "Customer {0,number,000}, {1}, has a balance of " +
            "{2,number,¤###,##0.00;(¤###,##0.00)}"; //}";
        MessageFormat msgFormat = new MessageFormat(pattern);
        Object[] msgArgs = 
        {
            new Integer(cust.getId()),
            cust.getName(),
            new Double(cust.getBalance())
        };
        System.out.println(msgFormat.format(msgArgs));
    }
    
    static class Customer
    {
        Customer(int id, String name, double balance)
        {
            m_id = id;
            m_name = name;
            m_balance = balance;
        }
        
        int     getId()     { return m_id; }
        String  getName()   { return m_name; }
        double  getBalance(){ return m_balance; }
        
        private int     m_id;
        private String  m_name;
        private double  m_balance;
    }
 }
 

which produces the following output:

Customer 001, Heather Gilmartin, has a balance of $200.00
Customer 002, Bill Gates, has a balance of ($3,000,000.00)
Customer 500, Crocodile Dundee, has a balance of $1,000.00
 
The page was last updated February 19, 2008