开发者

round number 105 or 95 to 100 in objective c

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!


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.


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.


One way to solve this:

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

Or slightly modified:

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


See here: Rounding numbers in Objective-C

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜