How to produce numbers in some step bounds?
I want to produce numbers with some steps, for example for step 4, i want to produce:
1 -> 0
3 -> 4
4.1 -> 4
15 -> 16
etc.
for step 0.2:
1 -> 1
3 -> 3
4.1 -> 4.2
15.99 -> 16
etc.
Do you know nice formula to produce numbers like these?开发者_JAVA技巧
It looks like you just want to round()
to the nearest multiple of step
. Try this:
result = round(num/step)*step
Step 4:
- round(1/4)*4=0*4=0
- round(3/4)*4=1*4=4
- round(4.1/4)*4=1*4=4
- round(15/4)*4=4*4=16
Step 0.2:
- round(1/0.2)*0.2=5*0.2=1
- round(3/0.2)*0.2=15*0.2=3
- round(4.1/0.2)*0.2=21*0.2=4.2
- round(15.99/0.2)*4=80*0.2=16
精彩评论