How to convert NSNumber objects for computational purposes?

馋奶兔 提交于 2019-12-19 05:14:19

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/1801197/how-to-convert-nsnumber-objects-for-computational-purposes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!