Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java rounding by specific step

Tags:

java

rounding

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...

like image 775
Sumedh Avatar asked Jun 20 '26 11:06

Sumedh


1 Answers

This will work for any step size:

public static float round(float input, float step) 
{
  return ((Math.round(input / step)) * step);
}
like image 128
thomson_matt Avatar answered Jun 22 '26 00:06

thomson_matt