使用 Java 中的 MessageFormat 类格式化百分比

要在 Java 中使用百分比填充符格式化消息,我们使用 MessageFormat 类。MessageFormat 类为我们提供了一种生成不依赖于语言的连接消息的方法。MessageFormat 类扩展了 Serializable 和 Cloneable 接口。

声明 - java.text.MessageFormat 类声明如下 -

public class MessageFormat extends Format

该  方法使用与参数编号和数组索引匹配的 params 数组中的对象来格式化消息并填充缺失的部分。MessageFormat.format(pattern, 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