Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding to specific value?

I need to round a number, let's say 543 to either the hundreds or the tens place. It could be either one, as it's part of a game and this stage can ask you to do one or the other.

So for example, it could ask, "Round number to nearest tens", and if the number was 543, they would have to enter in 540.

However, I don't see a function that you can specify target place value to round at. I know there's an easy solution, I just can't think of one right now.

From what I see, the round function rounds the last decimal place?

Thanks

like image 852
Austin Avatar asked Jan 14 '23 20:01

Austin


1 Answers

To rounding to 100's place

NSInteger num=543;

NSInteger deci=num%100;//43
if(deci>49){
    num=num-deci+100;//543-43+100 =600
}
else{
    num=num-deci;//543-43=500
}

To round to 10's place

NSInteger num=543;

NSInteger deci=num%10;//3
if(deci>4){
    num=num-deci+100;//543-3+10 =550
}
else{
    num=num-deci;//543-3=540
}

EDIT: Tried to merge the above in one:

NSInteger num=543;

NSInteger place=100; //rounding factor, 10 or 100 or even more.
NSInteger condition=place/2;

NSInteger deci=num%place;//43
if(deci>=condition){
    num=num-deci+place;//543-43+100 =600. 
}
else{
    num=num-deci;//543-43=500
}
like image 98
Anoop Vaidya Avatar answered Jan 19 '23 12:01

Anoop Vaidya