Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumberFormatter to show a maximum of 3 digits

I would like to make it so one of my UILabels only shows a maximum of 3 digits. So, if the associated value is 3.224789, I'd like to see 3.22. If the value is 12.563, I'd like to see 12.5 and if the value is 298.38912 then I'd like to see 298. I've been trying to use NSNumberFormatter to accomplish this, but when I set the maximum significant digits to 3 it always has 3 digits after the decimal place. Here's the code:

NSNumberFormatter *distanceFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[distanceFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[distanceFormatter setAlwaysShowsDecimalSeparator:NO];
[distanceFormatter setMaximumSignificantDigits:3];

I always thought 'significant digits' meant all the digits, before and after the decimal point. Anyway, is there a way of accomplishing this using NSNumberFormatter?

Thanks!

like image 368
benwad Avatar asked Mar 23 '12 16:03

benwad


2 Answers

I believe that

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.usesSignificantDigits = YES;
formatter.maximumSignificantDigits = 3;

will do exactly what you want, i.e. it will always show exactly 3 digits, be it 2 before the decimal and 1 after or 1 before the decimal and 2 after.

like image 168
DaGaMs Avatar answered Sep 28 '22 21:09

DaGaMs


Perhaps you also have to set (not sure though):

[distanceFormatter setUsesSignificantDigits: YES];

But in your case it's probably much easier to just use the standard string formatting:

CGFloat yourNumber = ...;
NSString* stringValue = [NSString stringWithFormat: @"%.3f", yourNumber];

(note: this will round the last digit)

like image 44
calimarkus Avatar answered Sep 28 '22 20:09

calimarkus