Dynamic integer will be any number from 0 to 150.
i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10.
Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?
Only thing is would also have to know if the number is 1, 2 or 3 digits (i.e. - 7 vs 94 vs 136)
Is there a better way to achieve this?
Thank You,
What about
((n + 9) / 10) * 10
?Yields 0 => 0, 1 => 10, 8 => 10, 29 => 30, 30 => 30, 31 => 40
How about using integer math:
in C, one-liner:
You can do this by performing integer division by 10 rounding up, and then multiplying the result by 10.
To divide
A
byB
rounding up, addB - 1
toA
and then divide it byB
using "ordinary" integer divisionSo, for your specific problem the while thing together will look as follows
This will "snap"
A
to the next greater multiple of 10.The need for the division and for the alignment comes up so often that normally in my programs I'd have macros for dividing [unsigned] integers with rounding up
and for aligning an integer to the next boundary
which would make the above look as
P.S. I don't know whether you need this extended to negative numbers. If you do, care should be taken to do it properly, depending on what you need as the result.
You could do the number mod 10. Then take that result subtract it from ten. Then add that result to the original.
Be aware that answers based on the div and mod operators ("/" and "%") will not work for negative numbers without an if-test, because C and C++ implement those operators incorrectly for negative numbers. (-3 mod 5) is 2, but C and C++ calculate (-3 % 5) as -3.
You can define your own div and mod functions. For example,