We are about to switch to a new forum software. Until then we have removed the registration on this forum.
hello all,
more simple way of a function to determine if a String is numeric?
Thank you all!
Best, Chrisir.... ;-)
void setup() {
println(isNumeric("---"));
}
void draw() {
//
}
boolean isNumeric(String testWord) {
// for int numbers, not float
// first we check if a wrong char is present
for (int i=0; i<testWord.length(); i++) {
if ("0123456789-".indexOf(testWord.charAt(i))<0) {
return false; // abort with false
}//if
}//for
// second: to avoid that testWord might be "---"
// we need to find one number at last
boolean foundOne = false;
for (int i=0; i<testWord.length(); i++) {
if ("0123456789".indexOf(testWord.charAt(i))>=0) {
foundOne = true;
}//if
}//for
if (!foundOne)
return false; // abort with false
// do we have a minus?
if (testWord.contains("-")) {
// only one minus allowed
int countMinus=0;
for (int i=0; i<testWord.length(); i++)
if (testWord.charAt(i)=='-')
countMinus++;
if (countMinus>1)
return false;
// -------------------
if (testWord.indexOf('-')!=0) // - must be first char like in -12
return false; // abort with false
}
return true; // success
}//func
Answers
Have you used regular expressions before?
Don't forget engineering format...
Ah, ok, ignore that last bit
(you can replace [0-9] with \\d but i think [0-9] is clearer)
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
so "-?[0-9]+" translates as "0 or 1 '-' symbols (the -? bit) followed by 1 or more digits (the [0-9]+ bit)"
Very impressive!!!
Thank you!!
You could use straight Java like this
You can also use
for other data types
that's probably better, yes 8) the exception is a bit fiddly though.
made a function that seems to work,
might give some false positives depending on how strict you want to be
negative zero is true
leading zeroes is true
super long numbers is true
Thanks!!