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