Most elegant way to detect if a String is a number?

前端 未结 11 830

Is there a better, more elegant (and/or possibly faster) way than

boolean isNumber = false;
try{
   Double.valueOf(myNumber);
   isNumber = true;
} catch (Nu         


        
11条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 12:17

    I prefer using a loop over the Strings's char[] representation and using the Character.isDigit() method. If elegance is desired, I think this is the most readable:

    package tias;
    
    public class Main {
      private static final String NUMERIC = "123456789";
      private static final String NOT_NUMERIC = "1L5C";
    
      public static void main(String[] args) {
        System.out.println(isStringNumeric(NUMERIC));
        System.out.println(isStringNumeric(NOT_NUMERIC));
      }
    
      private static boolean isStringNumeric(String aString) {
        if (aString == null || aString.length() == 0) {
          return false;
        }
        for (char c : aString.toCharArray() ) {
          if (!Character.isDigit(c)) {
            return false;
          }
        }
        return true;
      }
    

    }

提交回复
热议问题