使用Java MessageFormat格式化浮点数


在Java中,我们使用MessageFormat类来格式化包含浮点数的的消息。MessageFormat类提供了一种生成连接消息的方法,这种方法不依赖于语言。MessageFormat类扩展了Serializable和Cloneable接口。

声明 − java.text.MessageFormat类的声明如下:

public class MessageFormat extends Format

MessageFormat.format(pattern, params)方法格式化消息,并使用params数组中的对象填充缺失的部分,匹配参数编号和数组索引。

format方法有两个参数:模式和参数数组。模式包含在{}花括号中的占位符,这些占位符具有指示参数值存储在数组中位置的索引、指示填充物为数字的数字参数以及指示数字为浮点数的#.#参数。它们如下所示:

MessageFormat.format("{0,number,#.#} Hellos and {1,number,#.#} Worlds", obj);

让我们来看一个使用浮点填充物格式化消息的程序

示例

 在线演示

import java.text.MessageFormat;
public class Example {
   public static void main(String[] args) throws Exception {
      Object[] obj = new Object[] { new Float(23.21), new Float(56.86) };
      String message = MessageFormat.format("{0,number,#.#} Hellos and {1,number,#.#} Worlds", obj);
      System.out.println(message);
   }
}

输出

23.2 Hellos and 56.9 Worlds

请注意,浮点数已四舍五入到一位有效数字,即23.21已四舍五入到23.2,56.86已四舍五入到56.9。

Object[] obj = new Object[] { new Float(23.21), new Float(56.86) };

更新于:2020年6月25日

942 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.