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!
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;
}
}
Thanks for the comment and the code addition 🙂
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;
}
Cheers for the comment 🙂 I’ve added an updated version with both of the additions that have been mentioned.
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 guy for this work.
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;
}