determine if a String is numeric (only int, not float, but minus sign allowed)...?

edited July 2017 in Questions about Code

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...

  • for int numbers, not float

    Ah, ok, ignore that last bit

  • void setup() {
      test("120", true);
      test("124", true);
      test("1", true);
      test("-1", true);
    
      test("1-20", false);
      test("a", false);
      test("12d", false);
      test("", false);
      test("-", false);
    }
    
    void test(String str, boolean expected) {
      boolean actual = str.matches("-?[0-9]+"); // magic here
      if (actual == expected) {
        print("PASS: ");
      } else {
        print("FAIL: ");
      }
      println(str + " - " + expected);
    }
    
  • edited July 2017

    (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!!

  • Answer ✓

    You could use straight Java like this

    void setup() {
      isInteger("-2345");
      isInteger("-2.345");
      isInteger("2.345e6");
      isInteger("123.67");
      isInteger("9876");
    }
    
    boolean isInteger(String s) {
      boolean result = false;
      try {
        Integer.parseInt(s);
        result = true;
      }
      catch(NumberFormatException e) {
      }
      print(" The string'" + s +"' is ");
      if (result)
        println("an integer");
      else
        println("not an integer");
      return result;
    }
    

    You can also use

    Float.parseFloat
    Double.parseDouble
    Long.parseLong
    etc
    

    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

    boolean charIsNum(char c) {
      return 48<=c&&c<=57;
    }
    boolean isNumeric(String s) {
      char [] ca = s.toCharArray();
      int len =ca.length;
      boolean first = charIsNum(ca[0]);
      if (len==1) {
        return first;
      } else {
        if ( !first && ca[0]!='-') { 
          return false;
        }
        for (int i=1; i<len; i++) {
          if (!charIsNum(ca[i])) {
            return false;
          }
        }
      }
      return true;
    }
    void setup(){
     println(isNumeric("-")); // false
     println(isNumeric("A")); //false
     println(isNumeric("457-7534")); //false
     println(isNumeric("--3")); //false
    
     /*should these be true of false */
     println(isNumeric("-0")); //true ???
     println(isNumeric("0000034")); //true ???
     println(isNumeric("524610981869745432754265262564125532145")); // true ???
    
     println(isNumeric("0"));  // true
     println(isNumeric("9")); // true
     println(isNumeric("537")); // true
     println(isNumeric("-23234234")); // true
    }
    
  • Thanks!!

Sign In or Register to comment.