how to round number to custom step (0.25, 20, 100...)

  • Thread starter Thread starter ibiza
  • Start date Start date
I

ibiza

Hi all,

I'd need a function that would rounds values like :
d = roundTo(64.2, 0.25) ' returns 64.25
d = roundTo(64.2, 10) ' returns 64
d = roundTo(64.2, 100) ' returns 100

well, that rounds a value to the given step...with rounding up if it is
it is right in the middle (e.g. 1.25 to 1.5 with a step of 0.25)

can anyone help with this one?

Thanks! :)
 
Try this (in C#). It has not been tested. It might not be the best but I
think it will work.


public double roundTo(double numToRound, double step)
{

if (step == 0)
return numToRound;

//Calc the floor value of numToRound
double floor = ((long) (numToRound / step)) * step;

//round up if more than half way of step
double round = floor;
double remainder = numToRound - floor;
if (remainder > step / 2)
round += step;

return round;

}
 
I found a bug. The comparision in the if statement should be >= instead of >
if (remainder >= step / 2)
round += step;
 
ibiza said:
Hi all,

I'd need a function that would rounds values like :
d = roundTo(64.2, 0.25) ' returns 64.25
d = roundTo(64.2, 10) ' returns 64
d = roundTo(64.2, 100) ' returns 100

well, that rounds a value to the given step...with rounding up if it is
it is right in the middle (e.g. 1.25 to 1.5 with a step of 0.25)

can anyone help with this one?

Thanks! :)

Simply:

Shared Function RoundTo(value As Double, step As Double) As Double
Return Math.Round(value / step) * step
End Function

This will of course return the value 60 in the second case you listed,
not 64. I believe that's what you really intended.
 
wow, even simpler :)

and you got it right, the second case should have returned 60, my
mistake ;)
 
Back
Top