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.
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.
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).
Objective-C
(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]);
Swift
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 = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
Now you can simply do:
let someFloat = "42.42".numberValue
let someInt = "42".numberValue
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].
You can also do this:
NSNumber *number = #([dictionary[#"id"] intValue]]);
Have fun!
If you know that you receive integers, you could use:
NSString* val = #"12";
[NSNumber numberWithInt:[val intValue]];
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
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];
I think NSDecimalNumber will do it:
Example:
NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];
NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.
What about C's standard atoi?
int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);
Do you think there are any caveats?
You can just use [string intValue] or [string floatValue] or [string doubleValue] etc
You can also use NSNumberFormatter class:
you can also do like this code 8.3.3 ios 10.3 support
[NSNumber numberWithInt:[#"put your string here" intValue]]
NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:#"123.45"];
NSLog(#"My Number : %#",myNumber);
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.
Worked in Swift 3
NSDecimalNumber(string: "Your string")
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
extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
let someFloat = "12.34".numberValue
The code showing here assigns the value of an variables to the text field I want to do the opposite of that.
_Initial.text = [NSString stringWithFormat:#"%f", init];
The opposite of the code above. Please help
The opposite of that would be getting converting string to float. You can do it with this
init = [_Initial.text floatValue];
You should search for an answer before you ask a question.
NSString *intString = #"123";
NSString *floatString = #"456.789";
int intVal = [intString intValue];
float floatVal = [floatString floatValue];
printf("%i %f\n",intVal,floatVal);
I am having trouble trying to run this test due to an error on the first line of this code that states:
Incompatible pointer to integer conversion initializing 'int' with an
expression of type 'NSString *'
- (IBAction)Button:(id)sender
{
int x = TramNumber.text;
if (x < 9)
{
Tramresult.text = [NSString stringWithFormat:#"lol"];
}
else
{
NSLog (#"x is less than 9!");
}
}
#end
Please help. I am on iOS and running xCode 5.1.1 if that helps.
You are representing NSString value wrong.
Use this code sample to solve your problem:
int x = [TramNumber.text intValue];
To represent int value from your textfield.
int x = [TramNumber.text intValue];
You just need to convert NSString to int.
You cannot assign text as an integer.
You should cast NSString to int like this:
int x = [TramNumber.text intValue];
Just try this:
NSString *code = dic[#"code"];
int statusCode = [code intValue];
NSLog(#"%d",statusCode);
if(statusCode==1)//........cont...
This question already has answers here:
How do I convert an integer to the corresponding words in objective-c?
(7 answers)
Closed 8 years ago.
I am not sure how to explain this but I need something like this and I'm not quite sure how to do it. I have a textfield where the user enters a number. For example "200". I got a label that must show "Two Hundred"(The number entered in Words )
Any ideas on how to do this?
Thanks in advance sorry for my bad english
try this:
//textField.text is 200
NSInteger someInt = [textField.text integerValue];
NSString *numberWord;
NSNumber *numberValue = [NSNumber numberWithInt:someInt];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
numberWord = [numberFormatter stringFromNumber:numberValue];
NSLog(#"numberWord= %#", numberWord); // Answer: two hundred
yourLabel.text = numberWord;
You can use a NSNumberFormatter It can convert an NSNumber into its word representation.
NSNumber* number = #100;
NSString* textNumber;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
textNumber = [numberFormatter stringFromNumber:number];
Here's something totally different. A bit more complex and weird, but you can fiddle around with it if you seek more manual control over the output. This is set up to serve a value up to 100,000 (to demonstrate a conditional set up).
Have fun:
int theInteger = 1,123;
int convert1000 = 0;
int convert100 = 0;
int convert10 = 0;
int convert1 = 0;
NSString * wordThousand = #"Thousand";
NSString * wordHundred = #"Hundred";
NSArray *wordsArraySingleDigit = [[NSArray alloc] initWithObjects:#"Zero",#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight",#"Nine",nil];
NSArray *wordsArrayDoubleDigit = [[NSArray alloc] initWithObjects:#"Ten",#"Eleven",#"Twelve",...,#"Ninety Eight", #"Ninety Nine",nil];
convert1000 = (theInteger - (theInteger % 1000))/1000;
convert100 = ((theInteger - (convert1000 * 1000)) - ((theInteger - (convert1000 * 1000)) % 100))/100;
convert10 = ((theInteger - (convert1000 *1000)-(convert100 *100)) - ((theInteger -(convert1000 *1000) - (convert100 *100)) % 10))/10;
convert1 = (theInteger - (convert1000 *1000)-(convert100 *100) - (convert10 *10));
if (theInteger > = 10000 && < 100000){
NSString * convertedThousand = [wordsArrayDoubleDigit objectAtIndex : convert1000];
convertedThousand = [NSString stringWithFormat: #“%# %#“,convertedThousand,wordThousand];
NSLog (convertedThousand);
}
if (theInteger >= 1000 && <= 10000){
NSString * convertedThousand = [wordsArraySingleDigit objectAtIndex : convert1000];
convertedThousand = [NSString stringWithFormat: #“%# %#“,convertedThousand,wordThousand];
NSLog (convertedThousand);
}
NSString * convertedHundred = [wordsArraySingleDigit objectAtIndex : convert100];
convertedHundred = [NSString stringWithFormat: #“%# %#“, convertedHundred,wordHundred];
NSLog (convertedHundred);
NSString * convertedTen = [wordsArraySingleDigit objectAtIndex : convert10];
convertedTen = [NSString stringWithFormat: #“%#“, convertedTen];
NSLog (convertedTen);
NSString *convertedOne = [wordsArraySingleDigit objectAtIndex : convert1];
NSLog (convertedOne);
Hope this helps or gives you a starting point for an alternative approach.
I think you should account for every possibility and make a set of IF statements, for example, if the first digit of the number is 3, write "three", if the number has 4 digits, display "thousands"... of course you can organize your code to make the process easy.
I'm quite new to xcode and am making a app where you put two numbers in to a text input and I don't know how to make xcode to do the adding sum, I tried this but it did not work
self.answer.text = self.label.text + self.label2.text
Does anybody know how to do this.
Use :
NSInteger firstNumber=[self.label.text integerValue];
NSInteger secondNumber=[self.label2.text integerValue];
NSInteger total=firstNumber + secondNumber;
NSString *string=[NSString stringWithFormat:#"%d",total];
self.answer.text = string;
If you want to take double value replace integerValue with doubleValue
Here is another interesting way:
//Some string with expression which was taken from self.label.text
NSString *s = #"2*(2.15-1)-4.1";
NSExpression *expression = [NSExpression expressionWithFormat:s];
float result = [[expression expressionValueWithObject:nil context:nil] floatValue];
NSLog(#"%f", result);
self.answer.text=[NSString stringWithFormat:#"%f",result];