Rounding numbers to specific multiples

陌路散爱 提交于 2019-12-19 05:58:25

问题


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)

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/10456564/rounding-numbers-to-specific-multiples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!