# Thread: is a number? C function

1. ## is a number? C function

Hello.

Is there a function in C that check if a string is an int??.

2. You could use strtol to find out. If it returns zero check if the string is 0, if not then its not a number.

3. Thanks a lot. But is there a faster way? Like a isnumber() function?

4. What exactly do you want to achiev? strtol() converts the string into a long integer - if you don't actually need that, then you can check if each character "isdigit()", but if you are interested in using it as an integer value, you may just as well convert it and check if the conversion worked, and regardless of whether the result is zero or not, check with this method:
1. check that the passed in "endptr" is different from the original string (this ensures the string wasn't empty).
2. check that endptr points to a end-of-string zero ('\0', NUL).

That ensures that the passed in string was accepted as a whole - whether it contained only zero or something else.

--
Mats

5. 2. check that endptr points to a end-of-string zero ('\0', NUL).
Yeah I thought of that, but I wasent completely sure where the endptr would end up.

So yeah go with what matsp suggested its not a lot of code, and speed shouldent be an issue for this kind of stuff.

You could even wrap it into your own isnumber() function.

6. What I want to do is to check that a given string is a number and that this number is less than 900. I didn't use isdigit() function because I want to check the whole string.

For the second check I'm using:

if (strtol(string, NULL, 10) < 900) ...

So matsp, correct if I'm wrong, what you are proposing is this:

if (strtol(string, endptr 10) < 900)
if (!g_strrstr(string, endptr)....

7. I would do the check like this:
Code:
```char *endPtr;
int number = strtol(string, &endptr, 10);
// Two possible "endptr" scenarios:
// Nothing got parsed: string == endptr
// Or the whole string didn't get parsed: *endptr != '\0'
if (string == endptr || *endptr != '\0')
{
// Not a valid number
}
if (number > 900)
{
// Too big number
}```
I'm not sure if g_strstr will do the same thing or not, but it seems overly complicated compared to the first if-statement which, given a simple comment, should be clear to anyone.

--
Mats

8. Thanks a lot matsp. I will try it right now.

9. It works fine, but I'm having problems with negative numbers. The function doesn't recognize whether the number is greater or less than zero.

10. What do you mean, can you give an example, and perhaps post the code you are using for the "number detection". Negative numbers should be fine with strtol.

--
Mats

11. Nevermind, now it's working just fine. Thanks a lot for your help.

12. Originally Posted by mike_g
You could use strtol to find out. If it returns zero check if the string is 0, if not then its not a number.
hp so u gOt iT mIkeY