Formatting 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.

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);
		System.out.println(msg1);
		String msg2 = MessageFormat.format(
				"Message2 is {0,number} and {1,number}", obj1);
		System.out.println(msg2);
		String msg3 = MessageFormat.format(
				"Message3 is {0,number,#} and {1,number,#}", obj1);
		System.out.println(msg3);
		Object[] obj2 = new Object[] { new Double(123.45), new Double(1234.56) };
		String msg4 = MessageFormat.format(
				"Message4 is {0,number,#.#} and {1,number,#.#}", obj2);
		System.out.println(msg4);
		String msg5 = MessageFormat.format(
						"Message5 is {0,number,currency} and {1,number,currency}",
						obj2);
		System.out.println(msg5);
		String msg6 = MessageFormat.format(
				"Message6 is {0,number,percent} and {1,number,percent}", obj2);
		System.out.println(msg6);
	}
}

Output:

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%

Ads