I have a string that is being generate from a formula, however I only want to use the string as long as all of its characters are numeric, if not that I want to do something dif
For simple numbers like "12234" or "231231.23123" the answer can be simple.
There is a transformation law for int numbers: when string with integer transforms to int (or long) number and then, again, transforms it back to another string these strings will be equal.
In Objective C it will looks like:
NSString *numStr=@"1234",*num2Str=nil;
num2Str=[NSString stringWithFormat:@"%lld",numStr.longlongValue];
if([numStr isEqualToString: num2Str]) NSLog(@"numStr is an integer number!");
By using this transformation law we can create solution
to detect double
or long
numbers:
NSString *numStr=@"12134.343"
NSArray *numList=[numStr componentsSeparatedByString:@"."];
if([[NSString stringWithFormat:@"%lld", numStr.longLongValue] isEqualToString:numStr]) NSLog(@"numStr is an integer number");
else
if( numList.count==2 &&
[[NSString stringWithFormat:@"%lld",((NSString*)numList[0]).longLongValue] isEqualToString:(NSString*)numList[0]] &&
[[NSString stringWithFormat:@"%lld",((NSString*)numList[1]).longLongValue] isEqualToString:(NSString*)numList[1]] )
NSLog(@"numStr is a double number");
else
NSLog(@"numStr is not a number");
I did not copy the code above from my work code so can be some mistakes, but I think the main point is clear. Of course this solution doesn't work with numbers like "1E100", as well it doesn't take in account size of integer and fractional part. By using the law described above you can do whatever number detection you need.