java的格式化输出, 整数/小数/百分比及位置指定...



备忘一下

@Test
	public void testFmt(){
		System.out.println(String.format("%1$,d", 12345));		
		System.out.println(String.format("%1$8d", 12345));
		System.out.println(String.format("%1$08d", 12345));
		System.out.println(String.format("%1$.3f", 3.1415926));
		NumberFormat format = NumberFormat.getPercentInstance(Locale.US);
		format.setMinimumFractionDigits(1);
		System.out.println(format.format(0.1524));
		
		System.out.println(String.format("Second word:%2$s, First word: %1$s, Third  value :%3$.2f", "STR1", "STR2", 3.1415926));
	} 

 

输出结果:

12,345
   12345
00012345
3.142
15.2%
Second word:STR2, First word: STR1, Third  value :3.14

 

@Test
    public void teststr(){
        String lv1="Duit";
        System.out.println("'"+String.format("%1$-10s",lv1)+"'");
        System.out.println("'"+String.format("%1$10s",lv1)+"'");
        double lvV=3.1415;
        System.out.println("'"+String.format("%1$10.2f",lvV)+"'");
        System.out.println("'"+String.format("%1$-10.2f",lvV)+"'");

    }

 

 

'Duit      '
'      Duit'
'      3.14'
'3.14      '

 

你可能感兴趣的:(java)