将数字四舍五入到特定的倍数 [英] Rounding numbers to specific multiples

查看:218
本文介绍了将数字四舍五入到特定的倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能在Java中找到特定的倍数?
在excel中有 mround 函数,它可以很容易地四舍五入到指定的倍数,如下所示:

How can I round to a specific multiple in Java? In excel there is the mround function which allows for easy rounding to a specified multiple like so:

    mRound(variable,multiple)

所以<$ c $如果 x = 7.9 ,则返回 9 code> 6 if x = 7.2

so mRound(x,3) would return 9 if x = 7.9 and 6 if x = 7.2.

所有四舍五入我迄今为止发现的函数总是四舍五入到最接近的整数或指定的小数位数,但我希望能够更改每个变量的倍数。有没有人知道哪种功能最适合这种情况?

All of the rounding functions I have found so far always round to the nearest whole number or to a specified number of decimal places but I want to be able to change the multiple for each variable. Does anyone know what function would be best for this situation?

推荐答案

只需将数字除以数字,再乘以数字即可。

Just divide by the number, round, and multiply by the number.

double mRound(double value, double factor) {
    return Math.round(value / factor) * factor;
}

这篇关于将数字四舍五入到特定的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆