NSString - max 1 decimal of a float
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
I found the answer with NSNumberFormatter and setMaximumFractionDigits, then:
[numberFormatter stringFromNumber:myNumber]
Thanks to everyone especially @falconcreek
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
you could use %g like this
NSLog([NSString stringWithFormat: @"test: %g", (float)1.2]);
NSLog([NSString stringWithFormat: @"test: %g", (float)1])
NSNumberFormatter has changed a little bit recently. Here is an example of getting two significant digits rounding:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterNoStyle];
[numberFormatter setUsesSignificantDigits:YES];
[numberFormatter setMaximumSignificantDigits:2];
And here's a link to a good, recent resource.
精彩评论