String.format方法使用-浅析

本文详细解析了Java中String.format方法的使用,包括格式化字符串的基本语法、参数索引、标志、宽度、精度以及强制类型转换等内容。同时,介绍了如何处理不同数据类型的转换,如字符串、字符、整数、浮点数、布尔值、hash值等,并提供了丰富的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.代码中简单使用

String.format("%.2f", 2.0f);

2.源码调用的方法

 * Returns a localized formatted string, using the supplied format and arguments,
 * 返回本地化格式的字符串,使用提供的格式和参数
 * using the user's default locale.
 * 使用用户默认的本地语言环境
 * <p>If you're formatting a string other than for human
 * consumption, you should use the {@code format(Locale, String, Object...)}
 * 格式化字符串如果使用其他语言环境,你应该使用format(Locale, String, Object...)
 * overload and supply {@code Locale.US}. See
 * "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
 *
 * @param format the format string (see {@link java.util.Formatter#format})
 * @param args
 *            the list of arguments passed to the formatter. If there are
 *            more arguments than required by {@code format},
 *            additional arguments are ignored.
 * @return the formatted string.
 * @throws NullPointerException if {@code format == null}
 * @throws java.util.IllegalFormatException
 *             if the format is invalid.
 * @since 1.5
 */
public static String format(String format, Object... args) {
	return format(Locale.getDefault(), format, args);
}

public static String format(Locale locale, String format, Object... args) {  
    if (format == null) {  
        throw new NullPointerException("format == null");  
    }  
    int bufferSize = format.length() + (args == null ? 0 : args.length * 10);  
    Formatter f = new Formatter(new StringBuilder(bufferSize), locale);  
    return f.format(format, args).toString();  
}

3.相关类-Formatter

在Formatter类的释义中有如下信息:

Format strings consist of plain text interspersed with format specifiers, such as {@code “name: %s weight: %03dkg\n”}. Being a Java string, the usual Java string literal backslash escapes are of course available.

格式字符串由纯文本组成,其中穿插了格式说明符,如"name: %s weight: %03dkg\n"中的%s%03d。作为java字符串,反斜杠转移符也是支持的

Format specifiers (such as {@code “%s”} or {@code “%03d”} in the example) start with a {@code %} and describe how to format their corresponding argument. It includes an optional argument index, optional flags, an optional width, an optional precision, and a mandatory conversion type.

格式说明符以%开头,描述如何格式化相应参数。格式说明符包括可选的参数索引、可选的标记、可选的宽度、可选的精度、强制类型转换

3.1可选的参数索引

标记作用例子结果
%2$s中的2指定显示第2个参数format("%2 s , s,%1 s,s",“小明”,“小李”)小李,小明
<复用同一个参数format("%o %<d %<x", 64);100 64 40

3.2可选的标记

标记作用例子结果
,分割大数据format("%,d", 1024);1,234
+总是显示正数、负数符号format("%+d, %+4d", -5, 5);-5,   +5
非负数有一个前导空格String.format(“x% d% 5d”, 4, -4);x 4   -4
(把括号括在负数上format("%(d, %(d, %(6d", 12, -12, -12);12, (12),   (12)
-对齐
需要宽度;
-默认右对齐,-号左对齐;
format("%-6dx", 5);
format("%-3C,%3C", ‘d’, 0x65);
5     x
D  ,  E
0用前导零填充数字format("%07d, %03d", 4, 5555);0000004, 5555
#变形
仅八进制、十六进制;
format("%o %#o %d", 010, 010,010);
format("%x %#x %d", 0x12, 0x12,0x12);
10 010 8
12 0x12 18

3.3可选的宽度

The width is a decimal integer specifying the minimum number of characters to be used to represent the argument.

宽度是一个十进制整数,指定参数显示的最小字符数。
注:不能使用宽度来截断字段

标记作用例子结果
5前面有两个空格format("%3d",5);  5

3.4可选的精度

The precision is a {@code .} followed by a decimal integer

精度是.后面跟的整形数字

标记作用例子结果
.小数点后面跟几位format("%.1f", 123.456f);123.5

3.5强制类型转换

3.1非日期/时间转换类型
3.1.1字符串转换
标记作用例子结果
s字符串format("%s %s", “hello”, “Hello”);hello Hello
S大写字符串format("%S %S", “hello”, “Hello”);HELLO HELLO
3.1.2字符转换
标记作用例子结果
c字符format("%c %c", ‘d’, ‘E’);d E
C大写字符format("%C %C", ‘d’, ‘E’);D E
3.1.3整数转换
标记作用例子结果
d十进制format("%d", 26);26
o八进制format("%o", 032);32
x十六进制format("%x %X", 0x1a, 0x1a);1a 1A
3.1.4浮点数转换
标记作用例子结果
f十进制小数format("%f", 123.456f);
format("%.1f", 123.456f);
format("%1.5f", 123.456f);
format("%10f", 123.456f);
format("%6.0f", 123.456f);
123.456001
123.5
123.45600
123.456001
   123
e,E指数浮点数format("%e", 123.456f);
format("%.1e", 123.456f);
format("%1.5E", 123.456f);
format("%10E", 123.456f);
format("%6.0E", 123.456f);
1.234560e+02
1.2e+02
1.23456E+02
1.234560E+02
 1E+02
g,G十进制或指数取决于数的大小format("%g %g", 0.123, 0.0000123);0.123000 1.23000e-05
a,A十六进制小数format("%a", 123.456f);0x1.edd2f2p6
3.1.5布尔值转换

支持Boolean值。null被认为是false,其他类型实例为true

标记作用例子结果
b,B布尔值format("%b %b", true, false);
format("%B %B", true, false);
format("%b", null);
format("%b", “hello”);
true false
TRUE FALSE
false
true
3.1.6hash值转换

调用参数的hashCode方法,支持所有类型

标记作用例子结果
h,H十六进制hashcodeformat("%h", this);
format("%H", this);
format("%h", null);
190d11
190D11
null
3.1.7无参转换
标记作用例子结果
%输出%字符format("%d%%", 50);50%
n换行format(“first%nsecond”);first\nsecond
3.2日期/时间转换

日历、日期、毫秒值均可以作为日期/时间参数。如果类型有错误,则返回1970-01-01 00:00:00 UTC

标记作用例子结果
ta周内第几天(缩写)format("%ta", cal, cal);Tue
tA周内第几天(全)format("%tA", cal, cal);Tuesday
tb月份第几月(缩写))format("%tb", cal);Apr
tB月份第几月(全)format("%tB", cal);April
tc时间,请勿使用format("%tc", cal);Tue Apr 01 16:19:17 CEST 2008
tC世纪,两位数format("%tC", cal);20
td月份第几天,两位数format("%td", cal);01
tD美国日期格式,请勿使用format("%tD", cal);04/01/08
te月中的1天(1-31)format("%te", cal);1
tFISO 8601标准下的全面日期格式(YYYY-MM-DD)format("%tF", cal);2008-04-01
th%tb的同义词
tH2位数表示小时,24小时制(00-23)format("%tH", cal);16
tI2位数表示小时,12小时制(01-12)format("%tI", cal);04
tj三位数表示一年中的第几天(001-366)format("%tj", cal);092
tk表示小时,24小时制(0-23)format("%tk", cal);16
tl表示小时,12小时制(1-12)format("%tl", cal);4
tL毫秒数format("%tL", cal);359
tm2位数一年中的第几个月(01-12)format("%tm", cal);04
tM2位数分钟format("%tM", cal);08
tN纳秒format("%tN", cal);359000000
tp上午或下午format("%tp %Tp", cal, cal);pm PM
tQ自时代以来的毫秒值format("%tQ", cal);1207059412656
tr完整的12小时时间 %tI:%tM:%tS %Tpformat("%tr", cal);04:15:32 PM
tR短时24小时制format("%tR", cal);16:15
ts自时代以来的秒值format("%ts", cal);1207059412
tS两位数秒(00-60)format("%tS", cal);17
tT完整24小时制 %tH:%tM:%tSformat("%tT", cal);16:15:32
ty两位数年(00-99)format("%ty", cal);08
tY四位数年format("%tY", cal);2008
tz时间区格林尼治时间偏移format("%tz", cal);+0100
tZ本地时区缩写format("%tZ", cal);CEST
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值