Math常用的数学运算(包括取整、取绝对值、保留几位小数等)

本文详细介绍了Java Math类中用于数值计算的重要函数,包括求最大值、最小值、绝对值、四舍五入取整以及随机数生成等。通过实例展示了如何使用Math.max、Math.min、Math.abs、Math.round以及Math.random方法。此外,还提供了一个自定义函数SplitAndRound用于保留指定小数位数的四舍五入操作。
摘要由CSDN通过智能技术生成

返回两个数的最大值(支持int long float double)

System.out.println(Math.max(1,2));

返回两个数的最小值(支持int long float double)

System.out.println(Math.min(1,2));

返回一个数的绝对值(支持int long float double)

System.out.println(Math.abs(-15.6));

返回一个数四舍五入后取整(支持float double)注意, float型取整后是int型,而double取整后是long型。

System.out.println(Math.round(15.6));

返回向下取整的值(支持 double)

System.out.println(Math.floor(15.6));

返回大于等于0小于1的随机数

System.out.println(Math.random());

返回2的3次方

System.out.println(Math.pow(2,3));

保留n位小数:策略是先乘以10的n次方,取整后转化为浮点数,再除以10的n次方

System.out.println(SplitAndRound(2.3659,2));

    /**
     * 为num保留n位小数
     * @param num
     * @param n
     * @return
     */
    public static double SplitAndRound(double num, int n) {
        num = num * Math.pow(10, n);
        return (Math.round(num)) / (Math.pow(10, n));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

共饮一杯无

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

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

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

打赏作者

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

抵扣说明:

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

余额充值