Sunday, March 4, 2012

How do I format a message that contains number information?


import java.text.MessageFormat;
import java.util.Locale;

public class MessageFormatNumber {
    public static void main(String[] args) {

        //
        // Set the Locale for the MessageFormat.
        //
        Locale.setDefault(Locale.US);

        Integer[] numbers = new Integer[] {10, 75};

        //
        // Use the default formatting for number.
        //
        String message = MessageFormat.format("This is a {0} and {1} numbers", numbers);
        System.out.println(message);

        //
        // This line have the same format as above.
        //
        message = MessageFormat.format("This is a {0,number} and {1,number} numbers", numbers);
        System.out.println(message);

        Double[] doubles = new Double[] {25.7575, 75.2525};

        //
        // Format a number with 2 decimal digits.
        //
        message = MessageFormat.format("This is a formatted {0, number,#.##} and {1, number,#.##} numbers", doubles);
        System.out.println(message);

        //
        // Format a number as currency.
        //
        message = MessageFormat.format("This is a formatted currency {0,number,currency} and {1,number,currency} numbers", numbers);
        System.out.println(message);

        Double[] percents = new Double[] {0.10, 0.75};

        //
        // Format numbers in percentage.
        //
        message = MessageFormat.format("This is a formatted percentage {0,number,percent} and {1,number,percent} numbers", percents);
        System.out.println(message);
    }
}
Below is the output........

This is a 10 and 75 numbers
This is a 10 and 75 numbers
This is a formatted  25.76 and  75.25 numbers
This is a formatted currency $10.00 and $75.00 numbers
This is a formatted percentage 10% and 75% numbers

No comments:

Post a Comment