Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 341
Aspirasean Avatar asked Jun 12 '14 19:06

Aspirasean


2 Answers

Without the ceremony and with modern Objective C:

NSNumber *roundedUpNumber = @(ceil(self.field.text.doubleValue));
like image 97
Peter DeWeese Avatar answered Oct 16 '22 02:10

Peter DeWeese


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.
like image 5
David Xu Avatar answered Oct 16 '22 03:10

David Xu