ios 将浮点数转换为 NSNumber
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11371603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting float to NSNumber
提问by K17
I am missing something basic, here. Must have forgotten it. But basically, I have the following code the purpose take an NSNumber, convert it to float, multiply it by 2 and return the result to an NSNumber. I get an error on the last step, and am stumped. What should I do there.
我在这里缺少一些基本的东西。一定是忘记了。但基本上,我有以下代码,目的是获取 NSNumber,将其转换为浮点数,乘以 2 并将结果返回到 NSNumber。我在最后一步出错,并被难住了。我应该在那里做什么。
NSNumber *testNSNumber = [[[NSNumber alloc] initWithFloat:200.0f] autorelease];
float myfloatvalue = [testNSNumber floatValue] * -2;
NSLog(@" Test float value %1.2f \n\n",myfloatvalue);
[testNSNumber floatValue:myfloatvalue]; // error here is floatValue is not found
回答by dasblinkenlight
The method floatValue
of NSNumber
does not take parameters. If you would like to set a new float number, you need to re-assign testNSNumber
, because NSNumber
does not have a mutable counterpart:
该方法floatValue
的NSNumber
不带参数。如果你想设置一个新的浮点数,你需要重新分配testNSNumber
,因为NSNumber
没有可变的对应物:
testNSNumber = @(myfloatvalue); // The new syntax
or
或者
testNSNumber = [NSNumber numberWithFloat: myfloatvalue]; // The old syntax
回答by Mhdali
Swift 3.0:
斯威夫特 3.0:
let testNSNumber: NSNumber = NSNumber(value: myfloatvalue)
回答by brandonscript
Swift 2.0 version:
斯威夫特 2.0 版本:
let testNSNumber: NSNumber = NSNumber(float: myfloatvalue)