Java的格式化输出

参考https://www.cnblogs.com/qunqun/p/8656217.html

总结

  1. Formatter类,将一种形式的字符串转化为另一种形式,常用的System.out.format(),System.out.printf()和String.format()都是它的封装
    Usage:
String name = "huhx";
int age = 22;

Formatter formatter = new Formatter(System.out);
formatter.format("My name is %s, and my age is %d ", name, age);
formatter.close();

String msg = new Formatter().format("My name is %s, and my age is %d ", name, age).toString();

主要用法是format()方法,难点是格式化字符的使用

  1. 格式化字符的常见用法,参考https://blog.csdn.net/weixin_39590058/article/details/79875921
int year = 2020;
//直接打印数字
System.out.format("%d%n",year);		//用%n或\n没差,但%n和平台无关
//总长度为8,默认右对齐
System.out.printf("%8d%n",year);	//用printf还是format没差
//总长度为8,默认左对齐
System.out.printf("%-8d%n",year);
//总长度为8,不够补0
System.out.printf("%08d%n",year);
//千位分隔符
System.out.printf("%,8d%n",year*10000);
//小数点位数
System.out.format("%.2f%n",Math.PI);

补充一些
d 十进制
x 十六进制
o 八进制
f 浮点数
e 指数形式浮点数
s 字符串
c 字符
+保留正负号
3. 日期的格式化
都知道日期是从计算机纪元开始的时间戳转化的结构体
有两种方式可以对日期格式化
SimpleDateFormat 是Format的子类,但是与Formatter无关

Usage:

String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

Formatter本身也可以对日期格式化,但相对不那么方便(只能以某种规定的形式)
Usage

System.out.printf("%tc%n", new Date());
System.out.printf("%tF%n", new Date());
 System.out.printf("%tD%n", new Date());
 System.out.printf("%tT%n", new Date());
 System.out.printf("%tr%n", new Date());
 System.out.printf("%tR%n", new Date());
 System.out.printf("%tY%n", new Date());
 System.out.printf("%tm%n", new Date());
 System.out.printf("%td%n", new Date());
 System.out.printf("%ts%n", new Date());
 /**output:
星期一 九月 16 18:09:33 CST 2019
2019-09-16
09/16/19
18:09:34
06:09:34 下午
18:09
2019
09
16
1568628574(时间戳,以秒为单位,%tQ以毫秒为单位)
**/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值