繁体   English   中英

在Objective-C中指定精度的舍入数

[英]Round number to specified precision in Objective-C

我试图使用舍入的半舍入方法将数字舍入到指定的精度。 (即0.5将是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

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

使用NSDecimalNumber可获得更高的精度。 请参阅NSRoundingMode了解不同的舍入模式(我想你想要NSRoundPlain

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

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

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

对你想要的东西来说似乎有点过分,但它确保你的数字很少会失去精确度。

改变scale的争论的rounder更好的搜索结果更多的数字(即你的precision变量)。

尝试这个:

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

}

精度如下:2.1,舍入到.1将是1精度。 舍入为2将是0精度。 对于像12.4这样的东西,-1精度将是10.这是非常可靠的,我没有发现任何错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM