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).

其他提示

Try this:

-(double)roundNumber:(double)num toPrecision:(int)precision {

    double exact = num * pow(10, precision);
    double floor = floorl(exact);

    if ((floor + 1) <= (exact + 0.50)) {
        return (double) ((floor + 1) / pow(10, precision));
    }

    else
    {
        return (double) (floor / pow(10, precision));
    }

}

Where precision is the following: 2.1, rounding to .1 would be 1 precision. Rounding to 2 would be 0 precision. For something like 12.4, -1 precision would be 10. This is extremely reliable and I have not found any bugs in it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top