Round Up NSNumber
Asked Answered
S

3

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.

Shammer answered 12/6, 2014 at 19:47 Comment(1)
possible duplicate of How do I round a NSNumber to zero decimal spacesDigged
D
10

Without the ceremony and with modern Objective C:

NSNumber *roundedUpNumber = @(ceil(self.field.text.doubleValue));
Diplopod answered 12/6, 2014 at 20:25 Comment(1)
whoooaaaww… so nice :)Sergent
R
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.
Reinaldo answered 12/6, 2014 at 19:52 Comment(0)
A
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.

Abbotsen answered 12/6, 2014 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.