views:

327

answers:

3

Hi everyone,

I would like to use a float in a NSString. I used the stringWithFormat and a %f to integrate my float into the NSString. The problem is that I would like to display only one decimal (%.1f) but when there is no decimals I don't want to display a '.0' .

How can I do that?

Thanks

A: 

you could use %g like this

NSLog([NSString stringWithFormat: @"test: %g", (float)1.2]);
NSLog([NSString stringWithFormat: @"test: %g", (float)1])
Mark
doesn't work for 1.3333333333 for example!
ncohen
+2  A: 

You should use NSNumberFormatter.

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormat:@"#,##0.#"];
NSNumber *oneThousand = [NSNumber numberWithFloat:1000.0];
NSNumber *fivePointSevenFive = [NSNumber numberWithFloat:5.75];

NSLog(@"1000.0 formatted: %@", [numberFormatter stringFromNumber:oneThousand]);
NSLog(@"5.75 formatted: %@", [numberForatter stringFromNumber:fivePointSevenFive]);

There is a link in Apple's Data Formatting Programming Guide to the formatting standards. Handy Reference Number Format Patterns

falconcreek
Thanks but I'm developing on the iPhone and it doesn't support the setFormat...
ncohen
such a useful method. time to file a feature request on the bug reporter.
falconcreek
+1  A: 

I found the answer with NSNumberFormatter and setMaximumFractionDigits, then:

[numberFormatter stringFromNumber:myNumber]

Thanks to everyone especially @falconcreek

ncohen