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.
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).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments