java中怎么控制double的小数位数
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat( "0.0000 ");
double d1 = 1.0;
double d2 = 4.56789;
System.out.println(df.format(d1));
System.out.println(df.format(d2));
}
}
利用java.text.DecimalFormat可以设置double型数据的小数点位数,具体做法如下代码:
[java] view plain copy
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat( "0.00"); //设置double类型小数点后位数格式
double d1 = 2.1;
double d2 = 3.45678;
System.out.println(df.format(d1)); //将输出2.10
System.out.println(df.format(d2)); //将输出3.46(四舍五入)
}
}
推荐于2018-02-27
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat( "0.0000 ");
double d1 = 1.0;
double d2 = 4.56789;
System.out.println(df.format(d1));
System.out.println(df.format(d2));
}
}