数字的格式化
通过java.util.Formatter
/*数字格式化*/ /*整数*/ //%d参数必须与int相容 //%d表示以10进制整数的形式来显示 String s = String.format("I have %d apples.", 1000); System.out.println(s); //%,d表示以10进制整数带有逗号的形式来显示 s = String.format("I have %,d apples.", 1000); System.out.println(s); /*浮点数*/ //%参数必须是浮点数类型 //%f表示以浮点数保留6位小数点的形式显示 s = String.format("Pi is %f.", 3.1415926); System.out.println(s); //%.2f表示保留小数点后2位形式显示 s = String.format("The rank is %,d out of %,.2f.", 20456654, 100567890.248907); System.out.println(s); //%x参数必须是byte,short,int,long,BigInteger //以16进制显示 s = String.format("%x", 42); System.out.println(s); //%x参数必须是byte,short,int,long //ASCII码对应字符 s = String.format("%c", 42); System.out.println(s);
结果

关于日期的格式化
//%tc 完整的日期和时间 String dateStr = String.format("%tc", new Date()); System.out.println(dateStr); //星期三 四月 06 14:16:38 CST 2022 //%tr 只有时间 dateStr = String.format("%tr", new Date()); System.out.println(dateStr); //02:16:38 下午 //%tA - 星期几 //%tB - 月 //%tb - 日 Date today = new Date(); dateStr = String.format("%tA ,%<tB %<td", today); System.out.println(dateStr); //星期三 ,四月 06
懵懵懂懂迷迷糊糊

浙公网安备 33010602011771号