Skip to content

October 21, 2014

Work With Numbers in Objective C (NSNumber and NSDigitalNumber)

by noise

Next example shows you how to work with NSNumber and NSDecimalNumer objects in Objective C. First part show you standard use, second part shows how to work with NSNumer objects in simplified form and last part shows how to work with NSDecimalNumber objects.

In this example we define two NSNumber numbers and then we add them (or we muliply them).

NSNumber *a, *b, *c;
a = [NSNumber numberWithInt:10];
b = [NSNumber numberWithInt:20];
c = [NSNumber numberWithInt:([a intValue] + [b intValue])];
 
// short notations
a = @10;
b = @20;
c = @([a integerValue] * [b integerValue]);
 
// using NSDecimalNumbers
NSDecimalNumber *a1, *a2, *a3;
a1 = [[NSDecimalNumber alloc] initWithInt:15];
a2 = [[NSDecimalNumber alloc] initWithInt:30];
a3 = [a1 decimalNumberByMultiplyingBy:a2];
 
// define a boolean number
NSNumber *isItTrue = @YES;
 
// convert string to int
int val1 = [@"100" intValue];
NSNumber *d = [NSNumber numberWithInt:val1];
 
NSLog(@"\n isItTrue = %@ | d = %@", isItTrue, d);

You can also learn how to convert a NSString to a NSNumber object.

Working with NSNumbers to make computations is slow. Better use C type numbers instead. But anyway just in case you need this, it might be useful to know how to use NSNumber object to make mathematical operations.

Read more from Objective C Noise

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments