2009-09-19 15:48 阅读 982

如何将 NSString 转换为 NSNumber

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

Thanks for the help.


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

18条回答 默认 最新

  • 已采纳
    weixin_41568134 MAO-EYE 2009-09-19 16:21

    Use an NSNumberFormatter:

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

    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.

    点赞 27 评论 复制链接分享
  • weixin_41568174 from.. 2013-12-09 13:25


    (Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter)

    NSNumber *num1 = @([@"42" intValue]);
    NSNumber *num2 = @([@"42.42" floatValue]);


    Simple but dirty way

    // Swift 1.2
    if let intValue = "42".toInt() {
        let number1 = NSNumber(integer:intValue)
    // Swift 2.0
    let number2 = Int("42')
    // Swift 3.0
    NSDecimalNumber(string: "42.42") 
    // Using NSNumber
    let number3 = NSNumber(float:("42.42" as NSString).floatValue)

    The extension-way This is better, really, because it'll play nicely with locales and decimals.

    extension String {
        var numberValue:NSNumber? {
            let formatter = NSNumberFormatter()
            formatter.numberStyle = .DecimalStyle
            return formatter.number(from: self)

    Now you can simply do:

    let someFloat = "42.42".numberValue
    let someInt = "42".numberValue
    点赞 29 评论 复制链接分享
  • weixin_41568131 10.24 2009-09-19 16:18

    You can use -[NSString integerValue], -[NSString floatValue], etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:] which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter (including whether it will allow floating point values).

    点赞 23 评论 复制链接分享
  • csdnceshi71 Memor.の 2013-06-05 13:13

    You can also do this:

    NSNumber *number = @([dictionary[@"id"] intValue]]);

    Have fun!

    点赞 10 评论 复制链接分享
  • csdnceshi77 狐狸.fox 2017-07-07 06:33

    you can also do like this code 8.3.3 ios 10.3 support

    [NSNumber numberWithInt:[@"put your string here" intValue]]
    点赞 10 评论 复制链接分享
  • csdnceshi51 旧行李 2013-08-08 07:18
    NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:@"123.45"];
    NSLog(@"My Number : %@",myNumber);
    点赞 9 评论 复制链接分享
  • weixin_41568110 七度&光 2012-04-10 00:35

    If you know that you receive integers, you could use:

    NSString* val = @"12";
    [NSNumber numberWithInt:[val intValue]];
    点赞 7 评论 复制链接分享
  • csdnceshi58 Didn"t forge 2011-03-05 13:17

    Thanks All! I am combined feedback and finally manage to convert from text input ( string ) to Integer. Plus it could tell me whether the input is integer :)

    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber * myNumber = [f numberFromString:thresholdInput.text];
    int minThreshold = [myNumber intValue]; 
    NSLog(@"Setting for minThreshold %i", minThreshold);
    if ((int)minThreshold < 1 )
        NSLog(@"Not a number");
        NSLog(@"Setting for integer minThreshold %i", minThreshold);
    [f release];
    点赞 6 评论 复制链接分享
  • csdnceshi66 必承其重 | 欲带皇冠 2012-07-27 12:55

    What about C's standard atoi?

    int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);

    Do you think there are any caveats?

    点赞 6 评论 复制链接分享
  • csdnceshi53 Lotus@ 2013-09-14 14:39

    I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?

    All I pretty much did was:

    double myDouble = [myString doubleValue];
    点赞 6 评论 复制链接分享
  • weixin_41568183 零零乙 2013-07-20 08:57

    I think NSDecimalNumber will do it:


    NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];

    NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.

    点赞 4 评论 复制链接分享
  • csdnceshi64 游.程 2010-09-29 13:04

    For strings starting with integers, e.g., @"123", @"456 ft", @"7.89", etc., use -[NSString integerValue].

    So, @([@"12.8 lbs" integerValue]) is like doing [NSNumber numberWithInteger:12].

    点赞 2 评论 复制链接分享
  • csdnceshi65 larry*wei 2010-10-25 20:33

    Here's a working sample of NSNumberFormatter reading localized number NSString (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks ("8,765.4 " works), this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)

    NSString *tempStr = @"8,765.4";  
         // localization allows other thousands separators, also.
    NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
    [myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
    [myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
         // next line is very important!
    [myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial
    NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
    NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'", 
        tempStr, tempNum, [tempNum intValue]);
    [myNumFormatter release];  // good citizen
    点赞 2 评论 复制链接分享
  • csdnceshi77 狐狸.fox 2014-01-29 10:33

    You can just use [string intValue] or [string floatValue] or [string doubleValue] etc

    You can also use NSNumberFormatter class:

    点赞 2 评论 复制链接分享
  • csdnceshi68 local-host 2016-09-23 08:18

    Worked in Swift 3

    NSDecimalNumber(string: "Your string") 
    点赞 评论 复制链接分享
  • csdnceshi52 妄徒之命 2017-05-27 07:27

    I know this is very late but below code is working for me.

    Try this code

    NSNumber *number = @([dictionary[@"keyValue"] intValue]]);

    This may help you. Thanks

    点赞 评论 复制链接分享
  • csdnceshi77 狐狸.fox 2017-10-12 18:55
    extension String {
        var numberValue:NSNumber? {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            return formatter.number(from: self)
    let someFloat = "12.34".numberValue
    点赞 评论 复制链接分享
  • csdnceshi64 游.程 2017-11-02 06:23

    Try this

    NSNumber *yourNumber = [NSNumber numberWithLongLong:[yourString longLongValue]];

    Note - I have used longLongValue as per my requirement. You can also use integerValue, longValue, or any other format depending upon your requirement.

    点赞 评论 复制链接分享