使用 Java 中的 MessageFormat 类格式化百分比
java 8object oriented programmingprogramming
要在 Java 中使用百分比填充符格式化消息,我们使用 MessageFormat 类。MessageFormat 类为我们提供了一种生成不依赖于语言的连接消息的方法。MessageFormat 类扩展了 Serializable 和 Cloneable 接口。
声明 - java.text.MessageFormat 类声明如下 −
public class MessageFormat extends Format
MessageFormat.format(pattern, params) 方法使用 params 数组中的对象(匹配参数编号和数组索引)格式化消息并填充缺失部分。
format 方法有两个参数,一个模式和一个参数数组。该模式包含 {} 花括号中的占位符,其中有一个索引,指示参数值在数组中的位置,一个数字参数,指示填充符是数字,一个百分比参数,指示数字是百分比,代表百分比。它们如下 −
String message = MessageFormat.format("{0,number,percent} passed and {1,number,percent} failed", obj);
让我们看一个使用百分比填充符来格式化消息的程序 −
示例
import java.text.MessageFormat; public class Example { public static void main(String[] args) throws Exception { Object[] obj = new Object[] { new Double(40.56), new Double(59.44)}; String message = MessageFormat.format("{0,number,percent} passed and {1,number,percent} ailed", obj); System.out.println(message); } }
输出
输出如下 −
4,056% passed and 5,944% failed