How to convert an NSString into an NSNumber

后端 未结 18 2149
一整个雨季
一整个雨季 2020-11-22 16:56

How can I convert a NSString containing a number of any primitive data type (e.g. int, float, char, unsigned int

相关标签:
18条回答
  • 2020-11-22 17:13

    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
    
    0 讨论(0)
  • 2020-11-22 17:20
    NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:@"123.45"];
    NSLog(@"My Number : %@",myNumber);
    
    0 讨论(0)
  • 2020-11-22 17:20

    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.

    0 讨论(0)
  • 2020-11-22 17:21

    You can also do this:

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

    Have fun!

    0 讨论(0)
  • 2020-11-22 17:22

    What about C's standard atoi?

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

    Do you think there are any caveats?

    0 讨论(0)
  • 2020-11-22 17:22

    you can also do like this code 8.3.3 ios 10.3 support

    [NSNumber numberWithInt:[@"put your string here" intValue]]
    
    0 讨论(0)
提交回复
热议问题