Significant rounding

In Xcode / Objective-C for iPhone.

I have a float with a value of 0.00004876544. How can I make it display up to two decimal places after the first significant number?

For example, 0.00004876544 will read 0.000049.

+4
source share
1 answer

I did not run this through the compiler to double check it, but here is the main point of the algorithm (transformed 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; } 

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

+4
source

All Articles