Rounding with significant digits

女生的网名这么多〃 提交于 2019-12-01 06:53:28
Nate Thorn

I didn't run this through a compiler to double-check it, but here's the basic jist of the algorithm (converted from the answer to this question):

-(float) round:(float)num toSignificantFigures:(int)n {
    if(num == 0) {
        return 0;
    }

    double d = ceil(log10(num < 0 ? -num: num));
    int power = n - (int) d;

    double magnitude = pow(10, power);
    long shifted = round(num*magnitude);
    return shifted/magnitude;
}

The important thing to remember is that Objective-C is a superset of C, so anything that is valid in C is also valid in Objective-C. This method uses C functions defined in math.h.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!