在程序中有时会遇到保留小数点后特定n位的问题,今天在这里总结一下:
方法一:使用DecimalFormat来格式化
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer r = sc.nextInt();
//1.DecimalFormat的格式化结果是String类型的,想要结果为double需要再次强转。
DecimalFormat df = new DecimalFormat("#.0000000");
System.out.println(Double.parseDouble(df.format(Math.PI*r*r)));
}
}
方法二:使用Math.round()来保留位数
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer r = sc.nextInt();
//2.round() 方法可把一个数字舍入为最接近的整数
//原理是用round方法来将多余的位数舍弃掉,在还原到原来的位数
System.out.println((double)Math.round(Math.PI*r*r*10000000)/10000000);
}
}
方法三:使用String.format(args,args)来格式化,两个参数分别是格式化类型和待格式化的数。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer r = sc.nextInt();
//3.格式化为一个特定的字符串。
System.out.println(String.format("%.7f", Math.PI*r*r));
}
}
方法四:使用NumberFormat来保留小数
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer r = sc.nextInt();
//4.使用NumberFormat来保留小数。
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(7);
// 如果不需要四舍五入,可以使用RoundingMode.DOWN
nf.setRoundingMode(RoundingMode.UP);
System.out.println(nf.format(Math.PI*r*r));
}
}
如果您有其他的方法,欢迎留言讨论