How to convert an NSString into an NSNumber

后端 未结 18 2150
一整个雨季
一整个雨季 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:29

    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).

    0 讨论(0)
  • 2020-11-22 17:31
    extension String {
    
        var numberValue:NSNumber? {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            return formatter.number(from: self)
        }
    }
    
    let someFloat = "12.34".numberValue
    
    0 讨论(0)
  • 2020-11-22 17:33

    Worked in Swift 3

    NSDecimalNumber(string: "Your string") 
    
    0 讨论(0)
  • 2020-11-22 17:37

    I think NSDecimalNumber will do it:

    Example:

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

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

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

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

    NSString* val = @"12";
    [NSNumber numberWithInt:[val intValue]];
    
    0 讨论(0)
  • 2020-11-22 17:39

    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

    0 讨论(0)
提交回复
热议问题