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


為了給 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

更新於: 29-06-2020

191 次瀏覽

開啟你的 職業道路

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.