Page 1 of 1

rounding numbers to the nearest tick

Posted: Thu Oct 31, 2013 9:07 pm
by adventuresofgreg
Hello: I need a fast way of rounding a given number to it's nearest "tick" value. (the tick values change).

example:
number=100.19
tick = .25

in this case, given the tick value of .25, the only valid numbers between 100 and 101 are 100, 100.25, 100.5, 100.75 and 101
and in this case, 100.19 would round to 100.25

Thanks,
Greg K

Re: rounding numbers to the nearest tick

Posted: Thu Oct 31, 2013 9:18 pm
by Simon
Hi Greg,
Great problem!
What should happen if
number=100.125
tick = .25

Simon

Re: rounding numbers to the nearest tick

Posted: Thu Oct 31, 2013 9:20 pm
by dunbarx
Hi,

I would extract the decimal portion, and run a mod 25 and a div 25. So if you had XXX.66, 66 mod 25 would give you "16" and 66 div 25 would give you 2. If the mod is less than or equal to 12, you choose the div result, if greater, add 1 to the div result. Then just multiply the div result by 25 and reinsert back into the original number.

You will need to play around, I think , with values above XX.88 and below XXX.12. What I mean is,do test all over the range from 0-100.

Craig Newman

Re: rounding numbers to the nearest tick

Posted: Sat Nov 02, 2013 1:18 am
by [-hh]
..........

Re: rounding numbers to the nearest tick

Posted: Sat Nov 02, 2013 1:28 am
by dunbarx
Our resident mathematician is spot on, even though he is speaking in absolute terms.

That is two, Hermann.

But I would ask that Greg write his own handler to figure this out, and use your function after he has done that. Learning should be fun, but also arduous, or there is no triumph. Simon and I keep our silver platters close by.

Craig

Re: rounding numbers to the nearest tick

Posted: Wed Nov 06, 2013 11:28 am
by [-hh]
..........

Re: rounding numbers to the nearest tick

Posted: Wed Nov 06, 2013 3:30 pm
by dunbarx
Hermann.

Can't think of anything cute right now to forward my quest to learn about the second "h".

I agree with you about learning from reading existing code. But really new users need really simple code, or they just will not see what is going on. Your stuff is quite a bit beyond that. Anyway, it is just a matter of style, and I do like yours.

What does your "roundToEquallySpacedTicks" function do? The older one, which codifies my verbose hint, finds the nearest "0.25". What does this one find? I tried it with several arguments, and several values of "n", and it gives trunc(arg) no matter what.

Craig

Re: rounding numbers to the nearest tick

Posted: Wed Nov 06, 2013 5:42 pm
by [-hh]
..........

Re: rounding numbers to the nearest tick

Posted: Wed Nov 06, 2013 6:08 pm
by dunbarx
"Hermann" & "." & yetAnotherNewWrinkle & "." & "H"

Ah. I see.

Craig