package test;
public class PrintfTest {
class tes{}
public static void main(String[] args) {
// TODO 自动生成的方法存根
int a = 1;
PrintfTest t = new PrintfTest();
tes test = t.new tes();
//%d 继承Number的包装类或 整数的基本类型 和 BigInteger
System.out.printf("%d%%%n", a); //输出:1%
//%n换行符 windows-> /r/n linux-> /n Mac-> /r
System.out.printf("%f", 1.1234);//float double Float Double BigDecimal
// %e或%E 提供的数必须是Float、Double、float、double BigDecimal
System.out.printf("科学技术法 %e%n", (double)10987654321L);
System.out.printf("%S%n", "ac");//%s小写 %S大写 该例输出 : AC
System.out.printf("%S%n", test);//TEST.PRINTFTEST$TES@4554617C
int c = 15;
//提供的数 继承Number的包装类或 整数的基本类型和 BigInteger)
System.out.printf("八进制数 %o %n", c);//17
System.out.printf("十六进制数 %X", c);//%x或%X
//int short byte char Integer Short Byte Character
System.out.printf("字符符号 %c %C%n",(short)97,(short)97);
boolean flag = false;
System.out.printf("%b %B",flag,!flag);
//两个都输出584f463
System.out.printf("%h%n", s);
System.out.printf(Integer.toHexString(s.hashCode()));
}
}
格式控制
m.n
-m.n (忽略补空格)左对齐
0m.n 超出实际宽度的部分默认在数的最前面补0
- 输出小数
n精度(小数部分的位数 截尾) m域宽
实际宽度= n +1位(小数点算1位)+整数部分
输出宽度: m > 实际宽度? m :实际宽度 //超出实际宽度的部分默认在数的最前面补空格
可单独使用 如 %.2f 、%10d (.n 不能用于输出整型)
- 科学计数法
%m.nE
987654321 输出:9.876543E+08
n精度(还是小数点后的位数 四舍五入)
实际宽度= +n +4位固定部分( ‘小数点前的一位整数’、'.' 、''E+'')+指数部分(个位指数前补一位0 例如1.1E+06 )
987654321 " %8.1E" 输出: 9.9E+08 (前有一个空格)
- 输出字符串
m表示域宽 n表示截取字符串的位数
截取宽度 n> 实际宽度 ?实际宽度 : n
输出宽度: m > 截取宽度? m :截取宽度
- String s = "abcde";
- System.out.printf("%7S%n", s); // ABCDE
- System.out.printf("%.9S%n", s); //ABCDE
- System.out.printf("%5.2S%n", s); // AB