Java string.format() 方法是什麼?
Java string format()方法用於透過使用不同的格式說明符來格式化字串、整數、小數值等。此方法使用給定的區域設定、指定的格式化程序和參數傳回格式化的字串。如果未提供區域設置,則它將使用預設區域設定來格式化字串。string.format ()是 Java String類別的靜態方法。
public static String format(Locale loc, String format, Object… args)
public static String format(String format, Object… args)
參數
- 將應用於format()方法的區域設定值。
- 指定輸出字串的格式。
- 格式字串的參數數量範圍為 0 到多個。
- NullPointerException,如果格式為 null,則拋出NullPointerException 。
- IllegalFormatException,如果指定的格式非法,或提供的參數不足,則拋出此異常。
格式說明符
讓我們來看一些常用的說明詞。說明符 | 描述 |
---|---|
%s,%S | 字串格式化程式。 |
%d | 十進制整數,僅用於整數。 |
%o | 八進制整數,僅用於整數。 |
%f,%F | 對於十進制數,用於浮點數。 |
%x,%X | 十六進制整數,僅用於整數。 |
Java String.format() 方法範例
class Main {
public static void main(String[] args) {
// Integer value
System.out.println(String.format("%d", 234));
// String value
System.out.println(String.format("%s", "format() method"));
// Float value
System.out.println(String.format("%f", 99.99));
// Hexadecimal value
System.out.println(String.format("%x", 99));
// Char value
System.out.println(String.format("%c", 'f'));
// Octal value
System.out.println(String.format("%o", 99));
}
}
輸出
234 format()方法 99.990000 63 f 143
例子
class Main {
public static void main(String[] args) {
int n1 = 99;
// using two different specifiers for formatting the string
System.out.println(String.format("%s\nhexadecimal: %x", "Result is", n1));
}
}
輸出
結果是十六進位:63
例子
// to use Locale
import java.util.Locale;
class Main {
public static void main(String[] args) {
int number = 9999999;
// using the default locale if none specified
System.out.println(String.format("Number: %,d", number););
// using the GERMAN locale as the first argument
System.out.println(String.format(Locale.GERMAN, "Number in German: %,d", number));
}
}
輸出
編號:9,999,999 德文號碼:9.999.999
GO TO FULL VERSION