[JAVA基础]String的format

来源:互联网 发布:程序员客栈一个月收入 编辑:程序博客网 时间:2024/06/07 22:35

String类的格式化问题format:
(1)数字格式化
(2)日期格式化
两者都可以采用String类中的format方法(JDK1.5开始支持),格式化说明最多会包括5部分(不包括%符号)。[]中的都是可选内容,必要的部分是%和type,而且格式化说明的顺序是有规定的必须按照这个顺序来指定,规则如下所示:

%[argument number][flags][width][.precision]type

(1)argument number:如果要格式化的参数超过一个以上,可以在这里进行指定
(2)flags:特定类型的特定选项,例如数字用逗号,正负号等隔开
(3)width:最小字符数,这个不是输出的总的字符数,可以输出超过这个数值,如果不足的话就会主动补零
(4)precision精确度,前面有个圆点符号
(5)type:必填项,指定类型的标识
在格式化指令中一定要给类型,如果还需要指定其他项目的话,要把类型放在最后

package com.java.learn;import java.util.Date;public class StringFormat {    public static void main(String[] args) {        int num1 = 123456789;        double num2 = 12345678.321;        System.out.println(String.format("the int number is %,d and the double number is %,3f",num1,num2));        //the int number is 123,456,789 and the double number is 12,345,678.321000        System.out.println(String.format("the date is %tc",new Date()));        //the date is 星期四 十月 13 19:26:33 CST 2016        System.out.println(String.format("the date only has time is %tr",new Date()));        //the date only has time is 07:26:33 下午        Date date = new Date();        System.out.println(String.format("the date only has zhou and yue and ri is %tA,%tB %tC",date,date,date));        //the date only has zhou and yue and ri is 星期四,十月 20    }}
0 0
原创粉丝点击