5
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.

Aspirasean
  • 151
  • 2
  • 9
  • possible duplicate of [How do I round a NSNumber to zero decimal spaces](http://stackoverflow.com/questions/3388081/how-do-i-round-a-nsnumber-to-zero-decimal-spaces) – Sam B Jun 12 '14 at 19:54

3 Answers3

10

Without the ceremony and with modern Objective C:

NSNumber *roundedUpNumber = @(ceil(self.field.text.doubleValue));
Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
5

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.
Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76
David Xu
  • 5,555
  • 3
  • 28
  • 50
2

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.

Caleb
  • 124,013
  • 19
  • 183
  • 272