Share on Google+Share on Google+

Formatting a Message Containing a Number

In this section, you will learn how to format a message containing a number.

Formatting a Message Containing a Number

In this section, you will learn how to format a message containing a number.

You can also format the message that contains a number. The class MessageFormat provides advanced message formatting. It allows advanced value formatting, dependency on Locale and precompilation of the message. In the given example, we have used format() method of MessageFormat class to format the different patterns which includes percentage, currency etc. This method creates a MessageFormat with the given pattern and used it to format the given arguments.

Here is the code:

import java.text.*;

public class FormattingMessageWithNumber {
	public static void main(String[] args) {
		Object[] obj1 = new Object[] { new Integer(567), new Integer(5678) };
		String msg1 = MessageFormat.format("Message1 is {0} and {1}", obj1);
		String msg2 = MessageFormat.format(
				"Message2 is {0,number} and {1,number}", obj1);
		String msg3 = MessageFormat.format(
				"Message3 is {0,number,#} and {1,number,#}", obj1);
		Object[] obj2 = new Object[] { new Double(123.45), new Double(1234.56) };
		String msg4 = MessageFormat.format(
				"Message4 is {0,number,#.#} and {1,number,#.#}", obj2);
		String msg5 = MessageFormat.format(
						"Message5 is {0,number,currency} and {1,number,currency}",
		String msg6 = MessageFormat.format(
				"Message6 is {0,number,percent} and {1,number,percent}", obj2);


Message1 is 567 and 5,678
Message2 is 567 and 5,678
Message3 is 567 and 5678
Message4 is 123.4 and 1234.6
Message5 is $123.45 and $1,234.56
Message6 is 12,345% and 123,456%


Posted on: October 5, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null