Tom Kelly
Tom Kelly

Reputation: 509

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

Upvotes: 4

Views: 2464

Answers (1)

Nate Thorn
Nate Thorn

Reputation: 2183

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.

Upvotes: 4

Related Questions