java取出小数点后三位_java保留小数点后n位的四个方法总结

在程序中有时会遇到保留小数点后特定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));

}

}

如果您有其他的方法,欢迎留言讨论

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值