Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round number to specified precision in Objective-C

I am trying to round a number to a specified precision using the half round up method of rounding. (i.e. 0.5 would be 1 rounding to one's precision). I tried the following of another SO question, however it fails to round properly:

//where x is number and precision is precision
int num = floor(log10(abs(x))) - precision + 1;
double temp = pow(10, num);
return floor(x / temp + 0.5) * temp;

Example: 2.55 rounds to 2.5 whereas I need it to round to 2.6

I was wondering if anyone had a better method of rounding a number to a given precision. I have already tried modifying this method without success.

like image 653
arp000 Avatar asked Jan 23 '26 02:01

arp000


1 Answers

Use NSDecimalNumber for greater precision. See NSRoundingMode for the different rounding modes (I think you want NSRoundPlain)

NSDecimalNumberHandler *rounder = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:precision raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];

NSDecimalNumber *number;
NSDecimaNumber *rounded = [number decimalNumberByRoundingAccordingToBehavior:rounder];

See the docs for more info on the BOOL parameters in the handler.

It might seem like a bit of an overkill for what you want but it ensures your numbers will rarely lose precision.

Change the scale argument of the rounder for more digits on the result (i.e. your precision variable).

like image 136
Rich Avatar answered Jan 25 '26 18:01

Rich