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.

Hope that’s useful for someone!

6 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;
    }
    }

  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;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *