How can I convert a NSString
containing a number of any primitive data type (e.g. int
, float
, char
, unsigned int
You can just use [string intValue]
or [string floatValue]
or [string doubleValue]
etc
You can also use NSNumberFormatter class:
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.
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]
.
(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
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];
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");
}
else
{
NSLog(@"Setting for integer minThreshold %i", minThreshold);
}
[f release];