format.setMinimumFractionDigits(3);
String str = format.format(num);
System.out.println(str);
}
}
11、MessageFormat(动态文本)
(1)如果一个字符串中包含了多个与国际化相关的数据,可以使用MessageFormat类对这些数据进行批量处理。
(2)例如:
At 12:30 pm on jul 3,1998, a hurricance destroyed 99 houses and caused $1000000 of damage
以上字符串中包含了时间、数字、货币等多个与国际化相关的数据,对于这种字符串,可以使用MessageFormat类对其国际化相关的数据进行批量处理。
(3)MessageFormat 类如何进行批量处理呢?
1.MessageFormat类允许开发人员用占位符{0}{1}{2}…替换掉字符串中的敏感数据(即国际化相关的数据)。
2.MessageFormat类在格式化输出包含占位符的文本时,messageFormat类可以接收一个参数数组,以替换文本中的每一个占位符。
12、格式化模式字符串
(1)模式字符串:
On {0}, a hurricance destroyed {1} houses and caused {2} of damage.
(2)MessageFormat类
默认Locale
format(String pattern, Object... arguments) static
pattern 模式字符串
arguments 参数数组
自定义Locale
MessageFormat(String pattern, Locale locale)
format(Object obj)
String s = "At {0} on {1}, a hurricance destroyed {2} houses and caused {3} of damage";
Object[] args = { "12:30 pm", "jul 3,1998", "99", "$1000000" };
System.out.println(MessageFormat.format(s, args));
13、模式字符串与占位符
位符有三种方式书写方式:
(1){argumentIndex}: 0-9 之间的数字,表示要格式化对象数据在参数数组中的索引号
(2){argumentIndex,formatType}: 参数的格式化类型
(3){argumentIndex,formatType,FormatStyle}: 格式化的样式,它的值必须是与格式化类型相匹配的合法模式、或表示合法模式的字符串。
formatType:
number
date
time
choice
fomatStyle
short
medium
long
full
integer
currency
percent
Subformatpattern
String pattern = "At {0,time,short} on {0,date,medium},a destroyed {1}
houses and caused {2,number,currency} of damage."
Calendar calendar = Calendar.getInstance();
calendar.set(1998, 6, 3, 12, 30, 0);
Date date = calendar.getTime();
Object []msgArgs = {date, 99, 1000000};
String result = MessageFormat.format(pattern,msgArgs); // 默认国家
System.out.println(result);
// 动态文本高级应用
String s = "At {0,time,short} on {0,date,medium}, a hurricance destroyed {1,number,integer} houses and caused {2,number,currency} of damage";
// 第一个参数 日期对象12:30 pm on jul 3,1998
Calendar calendar = Calendar.getInstance();// 日历类
// 所有日期月份从0开始
calendar.set(1998, 6, 3, 12, 30, 0);
Date date = calendar.getTime();
// 第二个参数 99
int n = 99;
// 第三个参数 $1000000
int m = 1000000;
// 指定locale 是美国
MessageFormat messageFormat = new MessageFormat(s, Locale.US);
System.out.println(messageFormat.format(new Object[] { date, n, m }));
package com.itheima.i18n;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.junit.Test;
public class MessageFormatTest {
//At 12:30 pm on jul 3,1998, a hurricance destroyed 99 houses and caused $1000000 of damage
@Test
public void test1(){
String str = "At {0,date,full} {1,time,full}, a hurricance destroyed {2,number} houses and caused {3,number,currency} of damage";
MessageFormat format = new MessageFormat(str,Locale.CHINA);
Calendar c = Calendar.getInstance();
c.set(1998, 6, 3, 12, 30, 0);
Date date = c.getTime();
Object [] objs = {date,date,99,1000000};
String result = format.format(objs);
System.out.println(result);
}
}