我们经常需要将数字舍入为最小货币粒度的数量,如0.05.
我遇到了Java中的溢出问题,似乎已经解决了......希望您回顾一下这是否是一个正确的解决方案...此论坛上还有其他解决方案......
public static float round(float input, float step) {
float a = Math.round(input / step) * step;
//Can't return "a" directly because of overflow problem in some cases
int b = Math.round(a * 100);
return (float) (float)b / 100f; }
Run Code Online (Sandbox Code Playgroud)
但这只适用于2位小数位(如0.05),因为我在这里硬编码100 ...
这适用于任何步长:
public static float round(float input, float step)
{
return ((Math.round(input / step)) * step);
}
Run Code Online (Sandbox Code Playgroud)