Home  >  Article  >  Java  >  Summary of methods for determining whether a string is a number in java

Summary of methods for determining whether a string is a number in java

高洛峰
高洛峰Original
2017-01-16 10:48:331716browse

The example in this article summarizes Java's method of determining whether a string is a number. Share it with everyone for your reference, the details are as follows:

Method 1: Use the function that comes 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 will be helpful to everyone in Java programming.

For more java methods to determine whether a string is a number and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn