NSString - max 1 decimal float number

I would like to use float in NSString. I used stringWithFormat and% f to integrate my float into NSString. The problem is that I would like to display only one decimal number (% .1f), but when there are no decimal places, I do not want to display '.0'.

How can i do this?

thank

+3
source share
4 answers

I found the answer with NSNumberFormatter and setMaximumFractionDigits, then:

[numberFormatter stringFromNumber:myNumber]

Thanks to everyone especially @falconcreek

+3
source

You must 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]);

Apple . Handy Reference

+2

you can use% g like this

NSLog([NSString stringWithFormat: @"test: %g", (float)1.2]);
NSLog([NSString stringWithFormat: @"test: %g", (float)1])
+1
source

NSNumberFormatter has changed a bit lately. Here is an example of getting two significant rounding numbers:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterNoStyle];
[numberFormatter setUsesSignificantDigits:YES];
[numberFormatter setMaximumSignificantDigits:2];

And here is a link to a good recent resource.

0
source

Source: https://habr.com/ru/post/1743321/


All Articles