DecimalFormat 类主要靠 # 和 0 两种占位符号来指定数字长度。0 表示如果位数不足则以 0 填充,# 表示只要有可能就把数字拉上这个位置。用这个取小数的前几位,能够做到四舍五入。
System.out.println(new DecimalFormat("#.##%").format(pi)); //314.16%
System.out.println(new DecimalFormat("光速大小为每秒,###米。").format(c));
}
}
public static void main(String[] args){
doublepi=3.1415927; //圆周率
System.out.println(new DecimalFormat("0").format(pi)); //3
System.out.println(new DecimalFormat("0.00").format(pi)); //3.14
System.out.println(new DecimalFormat("00.000").format(pi));// 03.142
System.out.println(new DecimalFormat("#").format(pi)); //3
System.out.println(new DecimalFormat("#.##%").format(pi)); //314.16%
longc=299792458; //光速
System.out.println(new DecimalFormat("#.#####E0").format(c)); //2.99792E8
System.out.println(new DecimalFormat("00.####E0").format(c)); //29.9792E7
System.out.println(new DecimalFormat(",###").format(c)); //299,792,458
System.out.println(new DecimalFormat("光速大小为每秒,###米。").format(c));
}
}