Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSNumber objects for computational purposes?

Tags:

nsnumber

I an developing some code in which I use a scanner to get to NSNumbers from a string, say x and y.

Now I want to compute something simple from x and y, say, z = 10.0/(x + y/60.0)/60.0). I can't do this directly, since the compiler doesn't like ordinary arithmetic symbology applied to number objects.

So, I tried defining xD and yD, of type double, and then tried a type conversion

xD = (double) x; yD = (double) y;

but that also gives a compile error. Just how does one get NSNumber objects converted to be used in ordinary arithmetic expressions? I did considerable browsing of the literature, and didn't find the answer.

Thanks in advance for any help.

John Doner

like image 955
John R Doner Avatar asked Nov 26 '09 02:11

John R Doner


People also ask

What is NSNumber in Objective C?

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .

Why use NSNumber?

The purpose of NSNumber is simply to box primitive types in objects (pointer types), so you can use them in situations that require pointer-type values to work. One common example: you have to use NSNumber if you want to persist numeric values in Core Data entities.

What is __ NSCFNumber?

NSCFNumber is a concrete, "private" implementation of a class in that cluster. Just use the returned value like you would an NSNumber object.

Is NSInteger primitive?

It is not a C primitive (like int, unsigned int, float, double, etc.) NSInteger , CGFloat , NSUInteger are simple typedefs over the C primitives.


1 Answers

Use the "value" methods of the NSNumber class such as doubleValue.

// Initialized to something earlier
NSNumber * x, y;

//Convert NSNumbers to double
double xD = [x doubleValue]; 
double yD = [y doubleValue];

// You can now use regular arithmetic operators
double zD = 10.0 / ((x + y / 60.0) / 60.0);
like image 129
Ben S Avatar answered Sep 18 '22 11:09

Ben S