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!