Redneys
Redneys

Reputation: 305

How to display only significant decimals in UILabel?

I need to set a label to a number, which may or may not have decimals. I dont want it to be 5.00, just 5 (which may happen when using a standard token). Although, if there are significant decimals, like .56, then it should display 5.56; if it's .5, then it should display 5.56. Other than by just using a bunch of if-statements, how can I only show the decimals needed (i.e. is there a quick fix or do I need to do this manually)?

Upvotes: 0

Views: 269

Answers (1)

Jessedc
Jessedc

Reputation: 12460

In cocoa the best way to format number values for display is with NSNumberFormatter.

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumSignificantDigits:2];

NSNumber *significant = [NSNumber numberWithFloat:10.56f];
NSNumber *nonSignificant = [NSNumber numberWithFloat:10.00f];

NSLog(@"sig: %@, non-sig: %@", [formatter stringFromNumber:significant], [formatter stringFromNumber:nonSignificant]);
//sig: 10.56, non-sig: 10

Upvotes: 4

Related Questions