Java String.format() 方法的使用

String format 方法的使用
format(String format, Object… args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字符串。

format(Locale locale, String format, Object… args) 使用指定的语言环境,制定字符串格式和参数生成格式化的字符串。

1. %s:字符串类型,一个%s对应一个参数

System.out.println(String.format("Hello %s" , "World"));
System.out.println(String.format("Hello %s %s" , "World" , "Java"));

// 输出
Hello World
Hello World Java
1
2
3
4
5
6
2. %c:字符类型,一个%c对应一个字符

System.out.println(String.format("A %c" , 'B'));
System.out.println(String.format("A %c %c" , 'B' , 'C'));

// 输出
A B
A B C
1
2
3
4
5
6
3. %b:字符类型,一个%b对应一个布尔类型

System.out.println(String.format("%b %b" , 0 , 1));
System.out.println(String.format("1>2 %b 2>1 %b" , 1>2 , 2>1));

// 输出
true true
1>2 false 2>1 true
1
2
3
4
5
6
4. %d:整数类型(十进制),一个%d对应一个整数类型(十进制)

System.out.println(String.format("%d %d" , 12 , 13));

// 输出
12 13
1
2
3
4
5. %x:整数类型(十六进制),一个%x对应一个整数类型(十六进制)

System.out.println(String.format("%x %x" , 15 , 16));
// %06x 数字多少位就输出多少位,不够六位左右补零
System.out.println(String.format("%06x", 999));

// 输出
f 10
0003e7
1
2
3
4
5
6
7
6. %o:整数类型(八进制),一个%o对应一个整数类型(八进制)

System.out.println(String.format("%o %o" , 7 , 8));

// 输出
7 10
1
2
3
4
7. %f:浮点类型,一个%f对应一个浮点类型

// %f 浮点型输出,默认精确到小数点后六位
// %.5f 浮点型输出,保留小数点后5位,不够5位的零来补
System.out.println(String.format("%f %.2f %.5f", 7.0 , 8.0 , 9.99));

// 输出
7.000000 8.00 9.99000
1
2
3
4
5
6
8. %a:十六进制浮点类型,一个%a对应一个十六进制浮点类型

System.out.println(String.format("%a %a %a", 163.69 , 8.0 , 9.99));

// 输出
0x1.476147ae147aep7 0x1.0p3 0x1.3fae147ae147bp3
1
2
3
4
9. %e:指数类型,一个%e对应一个指数类型

System.out.println(String.format("%e %e %e", 163.69 , 8.0 , 9.99));

// 输出
1.636900e+02 8.000000e+00 9.990000e+00
1
2
3
4
10. %%:百分号,%n:换行

System.out.println(String.format("%d%% %n-%d%%", 123 , 666));

// 输出
123% 
-666%
1
2
3
4
5
11. 常见日期转换

Date date=new Date();

//c的使用
System.out.printf("全部日期和时间信息:%tc%n",date);
//f的使用
System.out.printf("年-月-日格式:%tF%n",date);
//d的使用
System.out.printf("月/日/年格式:%tD%n",date);
//r的使用
System.out.printf("HH:MM:SS PM格式(12时制):%tr%n",date);
//t的使用
System.out.printf("HH:MM:SS格式(24时制):%tT%n",date);
//R的使用
System.out.printf("HH:MM格式(24时制):%tR",date);

// 输出
全部日期和时间信息:星期四 九月 02 19:57:25 CST 2021
年-月-日格式:2021-09-02
月/日/年格式:09/02/21
HH:MM:SS PM格式(12时制):07:57:25 下午
HH:MM:SS格式(24时制):19:57:25
HH:MM格式(24时制):19:57
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

————————————————
版权声明:本文为CSDN博主「带你奔向远方」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41460654/article/details/120070387

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值