Search code examples
objective-cnsstringstringwithformat

NSString stringWithFormat problem


I have such a problem: double calcValue;

NSString *buf = [NSString stringWithFormat:@"%14f", myCalculator.calcValue];

buf = "7.142857";

istead of

buf = "7.1428571428571423";

I tried to format it in such ways: @"%f". But when I tried @"%14.9f" 9 signs after comma displayed.

Whats the problem? And how can I solve it? Thanx!


Solution

  • I'm not sure why, but stringWithFormat: doesn't seem to format doubles properly. You might try this approach:

    double calcValue=7.1428571428571423;
    NSString *buf=[[NSNumber numberWithDouble:calcValue] stringValue];
    

    which will set buf to @"7.142857142857142".

    For tighter control over number of digits, you could use a NSNumberFormatter.