Saturday, May 12, 2012

Rounding to the nearest Nth value.

What algorithm/equation should I use to round to the nearest Nth value?

Answer: Round(value2round/N)*N

Where N is the nearest number you want to round to and value2round is the number you are rounding.

I was asked, the other day, to create a digital clock using dropdown lists in Microsoft InfoPath that rounded to the nearest 5 minutes. I figured I would just look up the Round() math function and it would have a parameter to allow me to round to what ever number of minutes I wanted. The Round() function, like in most languages, only rounds to the nearest X decimal places. In the case of InfoPath to the nearest whole number.  I though I could divide by 10, then round the number, and multiply it by 10 then it would round to the nearest 10 (e.g. Round(22/10)*10 -> 20 and Round(25/10)*10 -> 30). I realized this will work for any number N where N is the nearest number you want to round to (e.g. Round(22/5)*5 -> 20 and Round(23/5)*5 -> 25). It was pretty obvious, but sometimes the most obvious thing can be hard to see. I hope this helps someone.

The one gotcha I found with InfoPath is that it wouldn't let me multiply a number. I had to create a field (constant) and assign the value to the field and then use the field name in the equation.

No comments: