How can I convert a NSString
containing a number of any primitive data type (e.g. int
, float
, char
, unsigned int
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).
extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
let someFloat = "12.34".numberValue
Worked in Swift 3
NSDecimalNumber(string: "Your string")
I think NSDecimalNumber will do it:
Example:
NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];
NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.
If you know that you receive integers, you could use:
NSString* val = @"12";
[NSNumber numberWithInt:[val intValue]];
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