Search code examples
objective-ccocoaprintfprecisionnslog

Only present number with precision if needed - is it possible?


Is there a possibility to present the same variable in different precisions?
For example, if I'm presenting an addition of two integers, it would be like:

result = 2+3;
NSLog(@"%.0f", result);

but with a division it would be like:

result = 2/3;
NSLog(@"%.1f", result);

Although presenting the π (pi) it would be like:

result = M_PI;
NSLog(@"%.19f", result); //And it would be 3.141592653589793238

Solution

  • NSNumber will do some quick-and-dirty formatting for you,

    NSNumber * five = [NSNumber numberWithDouble:3+2];
    NSNumber * twoThirds = [NSNumber numberWithDouble:2/3.0];
    NSNumber * mPi = [NSNumber numberWithDouble:M_PI];
    
    NSLog(@"%@", [five stringValue]);
    NSLog(@"%@", [twoThirds stringValue]);
    NSLog(@"%@", [mPi stringValue]);
    

    2011-11-17 21:52:12.621 Precision[13359:903] 5
    2011-11-17 21:52:12.624 Precision[13359:903] 0.6666666666666666
    2011-11-17 21:52:12.625 Precision[13359:903] 3.141592653589793

    but you should really use an NSNumberFormatter:

    NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
    
    [formatter setUsesSignificantDigits:YES];
    
    NSLog(@"%@", [formatter stringFromNumber:five]);
    NSLog(@"%@", [formatter stringFromNumber:twoThirds]);
    
    [formatter setMaximumSignificantDigits:16];
    NSLog(@"%@", [formatter stringFromNumber:mPi]);
    

    2011-11-17 21:52:12.629 Precision[13359:903] 5
    2011-11-17 21:52:12.630 Precision[13359:903] 0.666667
    2011-11-17 21:52:12.630 Precision[13359:903] 3.14159265358979

    The string format specifiers also allow variable precision; use an asterisk instead of a digit after the decimal point:

    int precision = 3;
    NSLog(@"%.*f", precision, 2/3.0);