# Arduino IsNumeric Function

I needed an “IsNumeric(string)” function for some Arduino code I’m writing and couldn’t find one in the libraries so I thought I’d share mine:

EDIT: updated version:

```boolean isNumeric(String str) {
unsigned int stringLength = str.length();

if (stringLength == 0) {
return false;
}

boolean seenDecimal = false;

for(unsigned int i = 0; i < stringLength; ++i) {
if (isDigit(str.charAt(i))) {
continue;
}

if (str.charAt(i) == '.') {
if (seenDecimal) {
return false;
}
seenDecimal = true;
continue;
}
return false;
}
return true;
}```
```boolean isNumeric(String str) {
for(char i = 0; i < str.length(); i++) {
if ( !(isDigit(str.charAt(i)) || str.charAt(i) == '.' )) {
return false;
}
}
return true;
}```

There are a few tweaks that should be added (such as counting decimal points as this would currently except 12.34.56 which is clearly not a valid number), this is a good starting point however. Done.

Hope that’s useful for someone!

## 7 thoughts on “Arduino IsNumeric Function”

1. Hi, thanks for your code. But I change a little. If I pass an empty string, the function is returning true. Then, first I test the string length, if the string is empty the function return false.
boolean IsNumeric(String str) {

if(str.length()){
Serial.println(str);
for(char i = 0; i < str.length(); i++) {
if ( !(isDigit(str.charAt(i)) || str.charAt(i) == '.' )) {
return false;
}
}
return true;
}
else{
return false;
}
}

1. Thanks for the comment and the code addition đź™‚

2. Made it even better, when I put warnings on I got a warning on unsigned and signed integers when you do i < str.length().
Now there is a check when you encounter a second . in the string.

boolean IsNumeric(String str)
{
if(str.length()<1){return false;}
bool bPoint=false;
for(unsigned char i = 0; i < str.length(); i++)
{
if ( !(isDigit(str.charAt(i)) || str.charAt(i) == '.' )|| bPoint) {return false;}
if(str.charAt(i) == '.'){bPoint=true;};
}
return true;
}

1. Cheers for the comment đź™‚ I’ve added an updated version with both of the additions that have been mentioned.

3. You can include negative numbers modifying the second “If” like this:

if (isDigit(str.charAt(i))) {
continue;
} else if ( i == 0 && str.charAt(0) == ‘-‘) {
continue;
}

Great job! Thanks!

Thanks for your job. I just added “+” and “-” caracters and the fuction trim() who eliminate spaces before and after the number.

boolean isNumeric(String str)
{
str.trim(); // line added: eliminate spaces, and \n before and after the string
unsigned int stringLength = str.length();

if (stringLength == 0) {
return false;
}
boolean seenDecimal = false;
for(unsigned int i = 0; i < stringLength; ++i)
{
if (i==0 && (str.charAt(0)=='+' || str.charAt(0)=='-')) // handle the "+" and "-" caracters only on the first place
continue;
if (isDigit(str.charAt(i)))
continue;
if (str.charAt(i) == '.')
{
if (seenDecimal)
return false;
seenDecimal = true;
continue;
}
return false;
}
return true;
}