how can I check if the NSString *val I have has a Integer or float ?? The raw approach is to look for "." character..but is there a more graceful way to do this?
Asked
Active
Viewed 3,754 times
3
-
Possible duplicate of http://stackoverflow.com/questions/565696/nsstring-is-integer – Alex Churchill Sep 03 '11 at 07:37
-
@alex c: Not a duplicate, handles only a part of what the poster wants. – DarkDust Sep 03 '11 at 07:41
-
@DarkDust: I see what you mean; I assumed OP knew he had a number (either int or float) and merely wanted to distinguish. I've posted an answer dealing with the general case. – Alex Churchill Sep 03 '11 at 07:53
-
3**Never** check for `.` explicitly - many countries use `,` rather than `.` as a decimal separator. – Paul R Sep 03 '11 at 08:08
-
possible duplicate of [How to convert an NSString into an NSNumber](http://stackoverflow.com/questions/1448804/how-to-convert-an-nsstring-into-an-nsnumber) – Dave DeLong Sep 04 '11 at 16:08
-
also possible duplicate of http://stackoverflow.com/questions/2518761/get-type-of-nsnumber – Dave DeLong Sep 04 '11 at 17:15
1 Answers
8
First, try [NSScanner scanInt:]
&& [NSScanner isAtEnd]
. If it returns YES
, then you have an int. scanInt
will scan forward as long as it can interpret the stream as an int. If isAtEnd
is YES, then the entire string could be interpreted as an int (so you have an int).
Otherwise, try [NSScanner scanDouble:]
. If it returns YES
, then you have a double.
If both return NO
, then you don't have either.

Alex Churchill
- 4,887
- 5
- 30
- 42
-
Hmmm, the only problem with that is that for example the input `1` will have both methods return `YES`, as will `1.3` (AFAICS). In the first case both will return the same parsed numbers, but not in the second case. I guess one has to just use `scanDouble:`, if it returns YES, check whether the double is "integer", for example with `fmod(value, 1) == 0`. If that check says the number is integer, simply cast it to integer. – DarkDust Sep 03 '11 at 08:21
-
1@DarkDust good point. I believe you could also just use `[NSScanner isAtEnd]` after `scanInt`; if YES, then you have an int. – Alex Churchill Sep 03 '11 at 16:32