Summary of Java methods for determining whether a string is a number

  • 2020-04-01 04:20:56
  • OfStack

This example summarizes the Java method for determining whether a string is a number. Share with you for your reference, as follows:

Method 1: use the functions that come with JAVA


public static boolean isNumeric(String str){
 for (int i = str.length();--i>=0;){  
  if (!Character.isDigit(str.charAt(i))){
  return false;
  }
 }
 return true;
}

Method 2: use regular expressions


public static boolean isNumeric(String str){ 
  Pattern pattern = Pattern.compile("[0-9]*"); 
  return pattern.matcher(str).matches();  
} 

Method 3: use ASCII code


public static boolean isNumeric(String str){
  for(int i=str.length();--i>=0;){
   int chr=str.charAt(i);
   if(chr<48 || chr>57)
     return false;
  }
  return true;
}

I hope this article has been helpful to you in Java programming.


Related articles: