开发者

Rounding with significant digits

In Xcode /Objective-C for the iPhone.

I have a float with the value 0.00004876544. How would I get it to display to two decimal places after the first significant number?

For example, 0.00004876544 would read 0.开发者_如何学JAVA000049.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜