Java rounding by specific step
Frequently we need to round a number like an amount for minimum currency granularity like 0.05.
I faced an overflow problem in Java, and have seemingly solved it...would like you to review if it's a correct solution...there are other solutions present on this forum as well...
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; }
But this will only work for 2 decimal place step (like 0.05开发者_StackOverflow) as I am hard coding 100 here...
This will work for any step size:
public static float round(float input, float step)
{
return ((Math.round(input / step)) * step);
}
If you work with hundreds of decimals, float
is not the type you need. May I redirect you to BigDecimal
?
精彩评论