format类实例详解
提示:以下是本篇文章正文内容,下面案例可供参考
1、java字符串格式化输出
代码如下(示例):
可用printf();
//%s字符串
System.out.println(String.format("I am %s", "jj"));
//%c字符
System.out.println(String.format("首字母是 %c", 'x'));
//%b布尔类型
System.out.println(String.format("this is %b", true));
//%d 十进制整数
System.out.println(String.format("十进制整数 %d", 34));
//%x 十六进制整数
System.out.println(String.format("十六进制整数 %x", 34));
//%o 八进制整数
System.out.println(String.format("八进制整数 %o", 34));
//%f 浮点
System.out.println(String.format("浮点 %f", 34.0));
//%a 十六进制浮点
System.out.println(String.format("十六进制浮点 %a", 34.0));
//%e 指数类型
System.out.println(String.format("指数 %e", 34.0));
//%g 通用浮点
System.out.println(String.format("通用浮点类型 %g", 34.0));
//%h 散列码
System.out.println(String.format("散列码 %h", 34));
//%% 百分比
System.out.println(String.format("百分比 %%"));
//%n 换行
System.out.println(String.format("换行 %n"));
//%tx 日期与事件类型,x代表不同的日期与时间转换符 %ty 年 %tm月 %te 日
System.out.println(String.format("日期与事件类型 %ty",Calendar.getInstance()));
System.out.println(String.format("日期与事件类型 %tm",Calendar.getInstance()));
System.out.println(String.format("日期与事件类型 %te",Calendar.getInstance()));
搭配转换符的使用
//为正数或负数添加符号
System.out.println(String.format("%+d", 10));
//%-?为左对齐
System.out.println(String.format("|%-5d|", 10));
//在整数之前添加指定数量空格
System.out.println(String.format("%04d", 10));
//以“,”对数字分组
System.out.println(String.format("%,f", 999999999.0));
//使用括号包含负数
System.out.println(String.format("%(f", -999999999.0));
//十六进制添加0x
System.out.println(String.format("%#x", 34));
//八进制添加0
System.out.println(String.format("%#o", 34));
//浮点数包含小数点
System.out.println(String.format("%#f", 34.0));
//格式化前一个转换符所描述的参数(小数后有一位)
System.out.println(String.format("%f 和%<3.1f", 34.0f));
System.out.println(String.format("%3.1f", 34.0f)); //
// x$代表是第几个变量
System.out.println(String.format("%2$d,%1$s", "a",1));
日期格式化
// tc 输出全部日期和时间信息
System.out.println(String.format("全部日期和时间信息%tc", new Date()));
// tF 年—月—日格式(要大写)
System.out.println(String.format("年—月—日格式%tF", new Date()));
// tD 月/日/年格式(要大写)
System.out.println(String.format("月/日/年格式%tD", new Date()));
// tR HH:MM:SS PM/AM格式
System.out.println(String.format("HH:MM:SS PM/AM格式 %tr", new Date()));
// (大写)tT HH:MM:SS 24小时制
System.out.println(String.format("HH:MM:SS(24小时)%tT", new Date()));
// (大写)tR HH:MM 24小时制
System.out.println(String.format("HH:MM(24小时)%tR", new Date()));
// tb 输出月份简称
System.out.println(String.format(Locale.US,"英文月份简称%tb", new Date()));
// tb 输出月份简称
System.out.println(String.format("本地月份简称%tb", new Date()));
// tB 输出月份全称
System.out.println(String.format(Locale.US,"英文月份全称%tB", new Date()));
// tB 输出月份全称
System.out.println(String.format("本地月份全称%tB", new Date()));
// ta 输出星期简称
System.out.println(String.format(Locale.US,"星期简称%ta", new Date()));
// tA 输出星期全称
System.out.println(String.format("星期全称%tA", new Date()));