如何将NSString转换为NSNumber

落花浮王杯 提交于 2020-10-24 04:03:10

问题:

How can I convert a NSString containing a number of any primitive data type (eg int , float , char , unsigned int , etc.)? 如何转换包含许多原始数据类型(例如intfloatcharunsigned int等)的NSString The problem is, I don't know which number type the string will contain at runtime. 问题是,我不知道字符串在运行时将包含哪种数字类型。

I have an idea how to do it, but I'm not sure if this works with any type, also unsigned and floating point values: 我有一个方法,但是我不确定这是否适用于任何类型,也适用于无符号和浮点值:

long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber]; 
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];

Thanks for the help. 谢谢您的帮助。


解决方案:

参考一: https://stackoom.com/question/64to/如何将NSString转换为NSNumber
参考二: https://oldbug.net/q/64to/How-to-convert-an-NSString-into-an-NSNumber
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!