使用MessageFormat格式化数字,日期

 

http://www.cppblog.com/biao/archive/2010/12/01/135119.html

如数字上加逗号,保留小数点后面两位(会自动四舍五入),百分比,货币等。

参考实例: http://www.java2s.com/Code/Java/Development-Class/MessageFormat.htm

import java.text.MessageFormat;


public class Test {

    public static void main(String[] args) {

        Object[] params = { new Integer(123), new Double(1222234.567) };

        String msg = MessageFormat.format("{0,number,percent} and {1,number,,###.##}", params);

        System.out.println(msg);

    }

}

=========

http://sunxboy.iteye.com/blog/273950

第一个例子使用静态的方法 MessageFormat.format ,它在内部创建一个只使用一次的 MessageFormat

 int planet = 7;
 String event = "a disturbance in the Force";

 String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     planet, new Date(), event);

输出为:

 At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.

下面的例子创建了一个可以重复使用的 MessageFormat 实例:

 int fileCount = 1273;
 String diskName = "MyDisk";
 Object[] testArgs = {new Long(fileCount), diskName};

 MessageFormat form = new MessageFormat(
     "The disk \"{1}\" contains {0} file(s).");

 System.out.println(form.format(testArgs));

不同 fileCount 值的输出:

 The disk "MyDisk" contains 0 file(s).
 The disk "MyDisk" contains 1 file(s).
 The disk "MyDisk" contains 1,273 file(s).

对于更复杂的模式,可以使用 ChoiceFormat 来生成正确的单数和复数形式:

 MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
 double[] filelimits = {0,1,2};
 String[] filepart = {"no files","one file","{0,number} files"};
 ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
 form.setFormatByArgumentIndex(0, fileform);

 int fileCount = 1273;
 String diskName = "MyDisk";
 Object[] testArgs = {new Long(fileCount), diskName};

 System.out.println(form.format(testArgs));

不同的 fileCount 值的输出:

 

 The disk "MyDisk" contains no files.
 The disk "MyDisk" contains one file.
 The disk "MyDisk" contains 1,273 files.

 

 

=============================================================

 

Java代码 复制代码  收藏代码
  1. MessageFormat 使用以下形式的模式:   
  2.   
  3. MessageFormatPattern:   
  4. String   
  5. MessageFormatPattern FormatElement String   
  6.   
  7. FormatElement:   
  8. { ArgumentIndex }   
  9. { ArgumentIndex , FormatType }   
  10. { ArgumentIndex , FormatType , FormatStyle }   
  11.   
  12. FormatType: one of   
  13. number date time choice   
  14.   
  15. FormatStyle:   
  16. short  
  17. medium   
  18. long  
  19. full   
  20. integer   
  21. currency   
  22. percent   
  23. SubformatPattern   
  24.   
  25. String:   
  26. StringPartopt   
  27. String StringPart   
  28.   
  29. StringPart:   
  30. ''  
  31. ' QuotedString '  
  32. UnquotedString   
  33.   
  34. SubformatPattern:   
  35. SubformatPatternPartopt   
  36. SubformatPattern SubformatPatternPart   
  37.   
  38. SubFormatPatternPart:   
  39. ' QuotedPattern '  
  40. UnquotedPattern  
MessageFormat 使用以下形式的模式:

MessageFormatPattern:
String
MessageFormatPattern FormatElement String

FormatElement:
{ ArgumentIndex }
{ ArgumentIndex , FormatType }
{ ArgumentIndex , FormatType , FormatStyle }

FormatType: one of
number date time choice

FormatStyle:
short
medium
long
full
integer
currency
percent
SubformatPattern

String:
StringPartopt
String StringPart

StringPart:
''
' QuotedString '
UnquotedString

SubformatPattern:
SubformatPatternPartopt
SubformatPattern SubformatPatternPart

SubFormatPatternPart:
' QuotedPattern '
UnquotedPattern

 

在 String 中,"''" 表示单引号。QuotedString 可以包含除单引号之外的任意字符;围绕的单引号被移除。UnquotedString 可以包含除单引号和左花括号之外的任意字符。因此,格式化后消息字符串为 "'{0}'" 的字符串可以写作 "'''{'0}''" 或 "'''{0}'''"。

在 SubformatPattern 中,应用了不同的规则。QuotedPattern 可包含除单引号之外的任意字符,但不移除围绕的单引号,因此它们可以由子格式解释。例如,"{1,number,$'#',##}" 将产生一个带井号的数字格式,结果如:"$#31,45"。 UnquotedPattern 可以包含除单引号之外的任意字符,但其中的花括号必须成对出现。例如,"ab {0} de" 和 "ab '}' de" 是有效的子格式模式,而 "ab {0'}' de" 和 "ab } de" 则是无效的。

http://terryjs.iteye.com/blog/768872

==================

一。

MessageFormat 提供了以与语言无关方式生成连接消息的方式。使用此方法构造向终端用户显示的消息。

MessageFormat 获取一组对象,格式化这些对象,然后将格式化后的字符串插入到模式中的适当位置。

注: MessageFormat 不同于其他 Format 类,因为 MessageFormat 对象是用其构造方法之一创建的(而不是使用 getInstance MessageFormat 本身不实现特定于语言环境的行为。特定于语言环境的行为是由所提供的模式和用于已插入参数的子格式来定义的。

 

 

MessageFormat运行开发者输出文本中的变量的格式。它是一个强大的类,就像下面的例子展示的那样:

Java代码
String message =   
  1.   "Once upon a time ({1,date}, around about {1,time,short}), there " +   
  2.   "was a humble developer named Geppetto who slaved for " +   
  3.   "{0,number,integer} days with {2,number,percent} complete user " +   
  4.   "requirements. ";   
  5.   Object[ ] variables = new Object[ ]   
  6.   { new Integer(4), new Date( ), new Double(0.21) }   
  7.   String output = MessageFormat.format( message, variables );   
  8.   System.out.println(output);   
String message =
  "Once upon a time ({1,date}, around about {1,time,short}), there " +
  "was a humble developer named Geppetto who slaved for " +
  "{0,number,integer} days with {2,number,percent} complete user " +
  "requirements. ";
  Object[ ] variables = new Object[ ]
  { new Integer(4), new Date( ), new Double(0.21) }
  String output = MessageFormat.format( message, variables );
  System.out.println(output); 

 

  隐藏在信息中的是描述输出的格式的一种短小的代码,范例的输出如下:
  
  Once upon a time (Nov 3, 2002, around about 1:35 AM), there was a humble developer
  named Geppetto who slaved for 4 days with 21% complete user requirements.
  假如相同的信息需要被重复输出但是变量的值不同,那么创建一个MessageFormat对象并给出信息。下面是上面的例子的修正版:
  

Java代码
//String output = MessageFormat.format(message, variables );   
  1.   //变为:   
  2.   MessageFormat formatter = new MessageFormat(message);   
  3.   String output = formatter.format(variables);   
//String output = MessageFormat.format(message, variables );
  //变为:
  MessageFormat formatter = new MessageFormat(message);
  String output = formatter.format(variables); 

 

  
  除了可以处理日期、时间、数字和百分数外,MessageFormat也可以处理货币,运行更多的数字格式的控制并且答应指定ChoiceFormat。
  
  MessageFormat是一个极好的类,它应该经常被使用但是现在还没有。它的最大的缺点是数据是被作为变量传递而不是一个Properties对象。一个简单的解决办法是写一个封装类,它会预解析字符串为格式化的结果,将Properties的key转换为一个数组索引,顺序是 Properties.keys( )返回的顺序。

 

二。例子

<!-- Generated by javadoc (build 1.6.0-beta2) on Fri Mar 09 12:51:16 CST 2007 -->

第一个例子 使用静态的方法 MessageFormat.format ,它在内部创建一个只使用一次的 MessageFormat

Java代码
int planet = 7;   
  1.  String event = "a disturbance in the Force";   
  2.   
  3.  String result = MessageFormat.format(   
  4.      "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",   
  5.      planet, new Date(), event);  
int planet = 7;
 String event = "a disturbance in the Force";

 String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     planet, new Date(), event);

 

输出为:

 At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
 

下面的例子创建了一个可以重复使用的 MessageFormat 实例:

Java代码
int fileCount = 1273;   
  1.  String diskName = "MyDisk";   
  2.  Object[] testArgs = {new Long(fileCount), diskName};   
  3.   
  4.  MessageFormat form = new MessageFormat(   
  5.      "The disk \"{1}\" contains {0} file(s).");   
  6.   
  7.  System.out.println(form.format(testArgs));  
int fileCount = 1273;
 String diskName = "MyDisk";
 Object[] testArgs = {new Long(fileCount), diskName};

 MessageFormat form = new MessageFormat(
     "The disk \"{1}\" contains {0} file(s).");

 System.out.println(form.format(testArgs));

 

不同 fileCount 值的输出:

 The disk "MyDisk" contains 0 file(s).
 The disk "MyDisk" contains 1 file(s).
 The disk "MyDisk" contains 1,273 file(s).
 

对于更复杂的模式,可以使用 ChoiceFormat 来生成正确的单数和复数形式:

Java代码
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");   
  1. double[] filelimits = {0,1,2};   
  2. String[] filepart = {"no files","one file","{0,number} files"};   
  3. ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);   
  4. form.setFormatByArgumentIndex(0, fileform);   
  5.   
  6. int fileCount = 1273;   
  7. String diskName = "MyDisk";   
  8. Object[] testArgs = {new Long(fileCount), diskName};   
  9.   
  10. System.out.println(form.format(testArgs));  
 MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
 double[] filelimits = {0,1,2};
 String[] filepart = {"no files","one file","{0,number} files"};
 ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
 form.setFormatByArgumentIndex(0, fileform);

 int fileCount = 1273;
 String diskName = "MyDisk";
 Object[] testArgs = {new Long(fileCount), diskName};

 System.out.println(form.format(testArgs));

 

不同的 fileCount 值的输出:

 The disk "MyDisk" contains no files.
 The disk "MyDisk" contains one file.
 The disk "MyDisk" contains 1,273 files.
 

如上例所示,可以以编程方式来创建 ChoiceFormat ,或使用模式创建。有关更多信息,请参阅 ChoiceFormat

Java代码
form.applyPattern(   
  1.    "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");  
 form.applyPattern(
    "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");

 

注: 从上面的例子可以看到,由 MessageFormat 中的 ChoiceFormat 所生成的字符串要进行特殊处理;'{' 的出现用来指示子格式,并导致递归。如果 MessageFormatChoiceFormat 都是以编程方式创建的(而不是使用字符串模式),那么要注意不要生成对其自身进行递归的格式,这将导致无限循环。

当一个参数在字符串中被多次解析时,最后的匹配将是解析的最终结果。例如,

Java代码
MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");   
  1. Object[] objs = {new Double(3.1415)};   
  2. String result = mf.format( objs );   
  3. // result now equals "3.14, 3.1"   
  4. objs = null;   
  5. objs = mf.parse(result, new ParsePosition(0));   
  6. // objs now equals {new Double(3.1)}  
 MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
 Object[] objs = {new Double(3.1415)};
 String result = mf.format( objs );
 // result now equals "3.14, 3.1"
 objs = null;
 objs = mf.parse(result, new ParsePosition(0));
 // objs now equals {new Double(3.1)}

 

同样,使用包含同一参数多个匹配项的模式对 MessageFormat 对象进行解析时将返回最后的匹配。例如,

Java代码   MessageFormat mf = new MessageFormat("{0}, {0}, {0}");   
  1.  String forParsing = "x, y, z";   
  2.  Object[] objs = mf.parse(forParsing, new ParsePosition(0));   
  3.  // result now equals {new String("z")}  
MessageFormat mf = new MessageFormat("{0}, {0}, {0}");
 String forParsing = "x, y, z";
 Object[] objs = mf.parse(forParsing, new ParsePosition(0));
 // result now equals {new String("z")}

 

 

同步

消息格式不是同步的。建议为每个线程创建独立的格式实例。如果多个线程同时访问一个格式,则它必须是外部同步的。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值