The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.text  [26 examples] > Messsages  [3 examples]

e324. Formatting a Message Containing a Number

    Object[] params = new Object[]{new Integer(123), new Integer(1234)};
    String msg = MessageFormat.format("There are {0} a''s and {1} b''s", params);
    // There are 123 a's and 1,234 b's
    
    msg = MessageFormat.format("There are {0,number} a''s and {1,number} b''s", params);
    // There are 123 a's and 1,234 b's
    
    // Use a custom format; see e311 Formatting a Number Using a Custom Format
    msg = MessageFormat.format("There are {0,number,#} a''s and {1,number,#} b''s", params);
    // There are 123 a's and 1234 b's
    
    // Floating point numbers
    params = new Object[]{new Double(123.45), new Double(1234.56)};
    msg = MessageFormat.format("There are {0,number,#.#} a''s and {1,number,#.#} b''s", params);
    // There are 123.4 a's and 1234.6 b's
    
    // Currency
    msg = MessageFormat.format("There are {0,number,currency} a''s and {1,number,currency} b''s", params);
    // There are $123.00 a's and $1,234.00 b's
    
    // Percent
    msg = MessageFormat.format("There are {0,number,percent} a''s and {1,number,percent} b''s", params);
    // There are 12,345% a's and 123,456% b's

 Related Examples
e325. Formatting a Message Containing a Time
e326. Formatting a Message Containing a Date

See also: Dates    Numbers    Times    Words and Sentences   


© 2002 Addison-Wesley.