Objective c 目标C中规定精度的舍入数

Objective c 目标C中规定精度的舍入数,objective-c,floating-point,double,precision,rounding,Objective C,Floating Point,Double,Precision,Rounding,我正在尝试使用半舍入法将数字舍入到指定的精度。(也就是说,0.5是1个四舍五入到1的精度)。我尝试了另一个SO问题的以下内容,但未能正确地进行取整: //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; 示例:2.55到2.5轮,而

我正在尝试使用半舍入法将数字舍入到指定的精度。(也就是说,0.5是1个四舍五入到1的精度)。我尝试了另一个SO问题的以下内容,但未能正确地进行取整:

//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;
示例:2.55到2.5轮,而我需要它到2.6轮

我想知道是否有人有更好的方法将数字四舍五入到给定的精度。我已经尝试过修改这个方法,但没有成功

试试这个:

-(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));
    }

}
-(双)轮号:(双)数字精度:(int)精度{
双精度=数值*功率(10,精度);
双地板=地板(精确);

如果((楼层+1)使用
NSDecimalNumber
以获得更高的精度。有关不同的舍入模式,请参阅(我想您需要
NSRoundPlain

有关处理程序中的
BOOL
参数的更多信息,请参阅

对于你想要的东西来说,这似乎有点过分,但它确保了你的数字很少会失去准确性


更改
舍入器的参数,以获得结果上的更多数字(即
精度
变量)。

“它无法正确舍入”-您使用了什么数字进行测试,得到了什么输出,您期望得到什么?是否
round
已经做了您想要做的事情?我更新了问题
scale
参数以匹配问题更新中的请求。此外,添加
number
未分配,因为我不知道您当前是如何获得数字的(是从
NSString
NSNumber
,等等)但请告诉我,我会更新我的答案。在阅读了内容后,我将其更改为
NSRoundPlain
,我认为这更合适。
NSDecimalNumberHandler *rounder = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:precision raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];

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