I want a function to round up an integer, like this
11 -> 20
12 -> 20
31 -> 40
39 -> 40
50 -> 50
what can i do ?
Asked
Active
Viewed 70 times
-3

lzwei
- 1
- 2
-
1Welcome to Stack Overflow! Pure code-writing requests are off-topic on Stack Overflow -- we expect questions here to relate to specific programming problems -- but we will happily help you write it yourself! Tell us [what you've tried](https://stackoverflow.com/help/how-to-ask), and where you are stuck. This will also help us answer your question better. – WhatsThePoint Dec 27 '17 at 08:50
-
`(source + 9) / 10 * 10` in case of non-negative numbers only; `(sourse + (source > 0 ? 9 : -9)) * 10 / 10` in general case; there's a possibility of the integer overflow if `source` is close to `int.MaxValue` or `int.MinValue` – Dmitry Bychenko Dec 27 '17 at 08:53
-
you can make a function like this: static int roundAsYouWant(int num){ return num % 10 == 0 ? num : ((Convert.ToInt32(num / 10)) * 10) + 10; } – FarukT Dec 27 '17 at 09:07
1 Answers
-3
You could do something like this:
var mod = (i % 10);
var result = mod > 0 ? (i + 10 - mod) : i;

Nitesh Kumar
- 1,774
- 4
- 19
- 26

Kamil Budziewski
- 22,699
- 14
- 85
- 105
-
2You aren't only calculating `result`, you are also changing `i`. I guess that is an undesired side effect. – Patrick Hofman Dec 27 '17 at 08:59
-
-
1
-
@PatrickHofman I've accepted his edit, because I wanted to make same edit :) – Kamil Budziewski Dec 27 '17 at 12:09