如何将 NSString 转换为 NSNumber [英] How to convert an NSString into an NSNumber

查看:36
本文介绍了如何将 NSString 转换为 NSNumber的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换包含多个任何原始数据类型(例如intfloatchar)的NSStringcode>、unsigned int 等)?问题是,我不知道字符串在运行时将包含哪种数字类型.

How can I convert a NSString containing a number of any primitive data type (e.g. int, float, char, unsigned int, etc.)? 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];

感谢您的帮助.

推荐答案

使用 NSNumberFormatter:

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42"];

如果字符串不是有效数字,则 myNumber 将为 nil.如果它是一个有效的数字,那么您现在拥有了所有 NSNumber 优点来确定它实际上是什么类型的数字.

If the string is not a valid number, then myNumber will be nil. If it is a valid number, then you now have all of the NSNumber goodness to figure out what kind of number it actually is.

这篇关于如何将 NSString 转换为 NSNumber的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆