NumberFormat和DecimalFormat
NumberFormat是Format类的子类,用于国际化格式输出,DecimalFormat是NumberFormat的子类。
对于小数点后位数控制的用法。
NumberFormat
public static void main(String[] arg){
double a = 2222.345;
//int b = Math.round(a);
//System.out.println(b);
NumberFormat nf= NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
String c = nf.format(a);
System.out.println(c);//输出结果为2222.35.
}
DecimalFormat
public static void main(String[] arg){
double a = 2222.345;
//int b = Math.round(a);
//System.out.println(b);
DecimalFormat df = new DecimalFormat("#.00");
String d = df.format(a);
System.out.println(d);//输出结果为2222.35
}
但是如果定义DecimalFormat df = new DecimalFormait("#.000000"),则小数点后数字会进行补位,结果为2222.345000。而nf.setMaximu,FractionDigits(6)则小数点后数位不会进行补位。