0

I have integer value, and need to round it, how to do that?

105 will be 110 103 will be 100

so classical rounding for decimals? thank you!

  • round(value/10)*10 doesnt work? – Chad May 17 '11 at 16:41
  • @Chad: There are solutions that don't need floating point, but if you do want to use floating point you need to make either sure that `value` is already a float or divide by `10.0`, otherwise you're doing an integer divide which is then casted to float. – DarkDust May 17 '11 at 16:47

4 Answers4

4

One more for you:

int originalNumber = 95; // or whatever
int roundedNumber = 10 * ((originalNumber + 5)/10);

Integer division always truncates in C, so e.g. 3/4 = 0, 4/4 = 1.

Tommy
  • 99,986
  • 12
  • 185
  • 204
3

I don't know the exact Objective-C syntax, byt general programming question. C-style:

int c = 105;
if (c % 10 >= 5) {
    c += 10;
}
c -= c % 10;

No floating point calculations required.

Vivien Barousse
  • 20,555
  • 2
  • 63
  • 64
  • Or, maybe c = 10 * ((c + 5)/10); ? If you wanted to avoid conditionals. – Tommy May 17 '11 at 16:47
  • @Tommy: You should provide that as an answer, because it's Yet Another Way of solving this problem :-) You're taking advantage of the fact that an integer division "loses information". – DarkDust May 17 '11 at 16:51
  • shame on me :)))) this = 10 * ((c + 5)/10) is great! and working! :) thank you and thank all! :) – vogueestylee May 17 '11 at 17:14
2

One way to solve this:

rounded = (value + 5) - ((value + 5) % 10);

Or slightly modified:

rounded = value + 5;
rounded -= rounded % 10;
DarkDust
  • 90,870
  • 19
  • 190
  • 224
1

See here: Rounding numbers in Objective-C

You could support floats or express your ints as floats (105.0).

Community
  • 1
  • 1
mr-sk
  • 13,174
  • 11
  • 66
  • 101
  • Note that to achieve what the poster wants by using floats, you would need to do `round(value / 10.0) * 10.0`. – DarkDust May 17 '11 at 16:46