4

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Tom Kelly
  • 519
  • 2
  • 4
  • 16
  • 1
    Would this work: http://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits – TreyA Jul 19 '11 at 17:16
  • Thanks TreyA i'm not sure its what i'm looking for. – Tom Kelly Jul 19 '11 at 17:23
  • 1
    @Tom Are you sure? The algorithm in the accepted answer looks good, you'd just have to convert it to C and it should work fine. – Nate Thorn Jul 19 '11 at 17:27
  • @Nate really, I just looked at the examples and it didn't seem to apply. I'm not very mathematical. and wouldn't know how to convert this to objective-c. any help? – Tom Kelly Jul 19 '11 at 17:40
  • possible duplicate of [How do I "round" a number to end in certain digits?](http://stackoverflow.com/questions/2012266/how-do-i-round-a-number-to-end-in-certain-digits) – jscs Jul 19 '11 at 18:18
  • There's also this question from a few hours ago: http://stackoverflow.com/questions/6749649/trim-a-floating-point-value – jscs Jul 19 '11 at 18:25
  • @Josh Neither of those are talking about *significant* digits. – Nate Thorn Jul 19 '11 at 18:48

1 Answers1

4

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.

Community
  • 1
  • 1
Nate Thorn
  • 2,133
  • 2
  • 21
  • 27