Java中Math.round()的用法

今天遇到了关于Math.round()的用法的基础题,发现自己还不是太熟悉,所以来总结一下下。


Java中的Math.round()方法是将浮点型进行“四舍五入”转换为int类型的一个方法。使用细节可以看例题:

小数点后第一位等于五时:

System.out.println(Math.round(-11.5)); -> 输出为 -11
System.out.println(Math.round(11.5)); -> 输出为 12

小数点后第一位小于五时:

System.out.println(Math.round(-11.41)); -> 输出为 -11
System.out.println(Math.round(11.41)); -> 输出为 11

小数点后第一位大于五时:

System.out.println(Math.round(-11.58)); -> 输出为 -12
System.out.println(Math.round(11.58)); -> 输出为 12

代码验证:

public class main {
    public static void main(String[] args) {

        System.out.println(Math.round(-11.5));
        System.out.println(Math.round(11.5));

        System.out.println(Math.round(-11.41));
        System.out.println(Math.round(11.41));

        System.out.println(Math.round(-11.58));
        System.out.println(Math.round(11.58));
    }
}

结果图:
在这里插入图片描述

一句话结论:将括号内的数 + 0.5 向下取整即为输出。

验证结论:

小数点后第一位等于五时:

System.out.println(Math.round(-11.5)); -> -11.5 + 0.5 = -11 向下取整输出为 -11
System.out.println(Math.round(11.5)); -> 11.5 + 0.5 = 12 向下取整输出为 12

小数点后第一位小于五时:

System.out.println(Math.round(-11.41)); -> -11.41 + 0.5 = -10.91 向下取整输出为 -11
System.out.println(Math.round(11.41)); -> 11.41 + 0.5 = 11.91 向下取整输出为 11

小数点后第一位大于五时:

System.out.println(Math.round(-11.58)); -> -11.58 + 0.5 = -11.08 向下取整输出为 -12
System.out.println(Math.round(11.58)); -> 11.58 + 0.5 = 12.05 向下取整输出为 12
  • 13
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木木是木木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值