Reputation: 151
NSNumberFormatter *formatNumber = [[NSNumberFormatter alloc] init];
[formatNumber setRoundingMode:NSNumberFormatterRoundUp];
[formatNumber setMaximumFractionDigits:0];
NSNumber *height = [formatNumber numberFromString:self.heightField.text];
NSNumber *width = [formatNumber numberFromString:self.widthField.text];
NSNumber *depth = [formatNumber numberFromString:self.depthField.text];
NSNumber *weight = [formatNumber numberFromString:self.weightField.text];
NSLog(@"height %@", height);
NSLog(@"width %@", width);
NSLog(@"depth %@", depth);
NSLog(@"weight %@", weight)
I'm trying to round up height, width, depth and weight from UITextField to the nearest integer but it's still showing the entire decimal point. Can someone assist with my code to round it up?
thx.
Upvotes: 5
Views: 4265
Reputation: 124997
The documentation is rather confusing and makes it sound like the limits you set on a NSNumberFormatter
instance apply to both string->number and number->string conversions. That's not actually the case, though, as described in by a The Boffin Lab post:
Easy, we just set up the NSNumberFormatter and it handles it for us. However, a bit of testing and some checking with Apple Technical Support later it appears that this only applies for the conversion of numbers into text. The documents do not make it clear that in this case ‘input’ specifically means an NSNumber and that this setting is not used when converting in the other direction...
So, use the standard C functions like ceil()
, round()
, floor()
, etc. to adjust the number instead.
An alternative is to subclass NSNumberFormatter
so that it does respect the criteria in both directions.
Finally, if you really like slow code, or if you just want to get something mocked up, you could apply the formatter three times: string->number->string->number
That'd look like this*:
NSNumber *n = [formatNumber numberFromString:
[formatNumber stringFromNumber:
[formatNumber numberFromString:@"1.2345"]]];
*Kids, don't try this at home.
Upvotes: 2
Reputation: 18333
Without the ceremony and with modern Objective C:
NSNumber *roundedUpNumber = @(ceil(self.field.text.doubleValue));
Upvotes: 10
Reputation: 5597
You can use this
NSString *numericText = self.field.text;
double doubleValue = [numericText doubleValue];
int roundedInteger = ceil(doubleValue);
NSNumber *roundedUpNumber = [NSNumber numberWithInt:roundedInteger];
Summary:
double
Upvotes: 5