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) 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With