JDK5.0允许java像C语言那样直接用printf()方法来格式化输出

System.out.format()功能与printf()一样,可以使用%d,%f等参数。

使用System.out.format()完成左对齐,补0,千位分隔符,小数点位数,本地化表达

public class TestNumber {
   
    public static void main(String[] args) {
        int year = 2020;
        //左对齐,补0,千位分隔符,小数点位数,本地化表达
        
      //直接打印数字
        System.out.println(year);
          
        //直接打印数字
        System.out.format("%d%n",year);
        //总长度是8,默认右对齐
        System.out.format("%8d%n",year);
        //总长度是8,左对齐
        System.out.format("%-8d%n",year);
        //总长度是8,不够补0
        System.out.format("%08d%n",year);
        //千位分隔符
        System.out.format("%,8d%n",year*10000);
  
        //保留5位小数
        System.out.format("%.5f%n",Math.PI);
          
        //不同国家的千位分隔符
        System.out.format(Locale.FRANCE,"%,.2f%n",Math.PI*10000);
        System.out.format(Locale.US,"%,.2f%n",Math.PI*10000);
        System.out.format(Locale.UK,"%,.2f%n",Math.PI*10000);
          
    }
}

 输出结果:

2020
2020
    2020
2020    
00002020
20,200,000
3.14159
31?415,93
31,415.93
31,415.93

 

posted @ 2022-05-22 17:34  锐洋智能  阅读(60)  评论(0编辑  收藏  举报