Aspirasean
Aspirasean

Reputation: 151

Round Up NSNumber

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

Answers (3)

Caleb
Caleb

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

Peter DeWeese
Peter DeWeese

Reputation: 18333

Without the ceremony and with modern Objective C:

NSNumber *roundedUpNumber = @(ceil(self.field.text.doubleValue));

Upvotes: 10

David Xu
David Xu

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:

  • doubleValue converts your field to a double
  • ceil rounds the double up to the nearest integer
  • casting to int converts the double to an integer
  • construct the NSNumber from the integer.

Upvotes: 5

Related Questions