Java数学工具类Math的Math.round()方法

本文介绍了Java中Math类的round()方法,用于进行四舍五入操作。方法接受double或float类型的参数,返回最接近的int或long值。通过实例展示了四舍六入的规则,以及当数字以0.5结尾时如何进行取整。理解round()方法对于处理数值计算至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java数学工具类Math的Math.round()方法

1.概述

java.util.Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算相关的操作。

round() 方法返回一个最接近的 int、long 型值,四舍五入。

round 表示"四舍五入",**算法为Math.floor(x+0.5)**即将原来的数字加上 0.5 后再向下取整所以 Math.round(11.5) 的结果为 12,Math.round(-11.5) 的结果为 -11。

2.语法

该方法有以下几种语法格式:

  • long round(double d)
  • int round(float f)

3.参数

  • d – double 或 float 的原生数据类型
  • f – float 原生数据类型

4.记忆口诀和代码案例

public static long round(double num);四舍六入五成双(看下面代码的注释),round有大约,完整的意思

public class MathMethod {
    public static void main(String[] args) {
        //【注意,面试高频】round方法,四舍 六入 五成双
        //先看看四舍六入,如果出现负数,先转成正数,再四舍六入,最后加上负号
        System.out.println(Math.round(3.4));//3
        System.out.println(Math.round(3.6));//4
        System.out.println(Math.round(-3.4));//-3
        System.out.println(Math.round(-3.6));//-4

        //五成双是什么意思呢?当出现0.5结尾的时候,就给它再加上+0.5,5不就成双了,接着再对相加的结果进行floor运算
        System.out.println(Math.round(-2.5));//-2
        /**public static double floor(double num);向下取整,floor是地板的意思
         * floor方法,向下取整,往小的靠*/
        System.out.println(Math.floor(-2.5 + 0.5)); //-2.0 与Math.round(-2.5)结果一致

        System.out.println(Math.round(2.5)); //3
        System.out.println(Math.floor(2.5 + 0.5)); //3.0 与Math.round(2.5)结果一致
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

FBI HackerHarry浩

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

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

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

打赏作者

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

抵扣说明:

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

余额充值