zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JAVAC语言方法输出 直接 格式化 允许 printf
2023-09-27 14:21:31 时间

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