How to check if a String is numeric in Java

2018-12-31 01:02发布

How would you check if a String was a number before parsing it?

30条回答
十年一品温如言
2楼-- · 2018-12-31 01:48

if you are on android, then you should use:

android.text.TextUtils.isDigitsOnly(CharSequence str)

documentation can be found here

keep it simple. mostly everybody can "re-program" (the same thing).

查看更多
十年一品温如言
3楼-- · 2018-12-31 01:50

Parallel checking for very long strings using IntStream

In Java 8, the following tests if all characters of the given string are within '0' to '9'. Mind that the empty string is accepted:

string.chars().unordered().parallel().allMatch( i -> '0' <= i && '9' >= i )
查看更多
荒废的爱情
4楼-- · 2018-12-31 01:51

This is the fastest way i know to check if String is Number or not:

public static boolean isNumber(String str){
  int i=0, len=str.length();
  boolean a=false,b=false,c=false, d=false;
  if(i<len && (str.charAt(i)=='+' || str.charAt(i)=='-')) i++;
  while( i<len && isDigit(str.charAt(i)) ){ i++; a=true; }
  if(i<len && (str.charAt(i)=='.')) i++;
  while( i<len && isDigit(str.charAt(i)) ){ i++; b=true; }
  if(i<len && (str.charAt(i)=='e' || str.charAt(i)=='E') && (a || b)){ i++; c=true; }
  if(i<len && (str.charAt(i)=='+' || str.charAt(i)=='-') && c) i++;
  while( i<len && isDigit(str.charAt(i)) ){ i++; d=true;}
  return i==len && (a||b) && (!c || (c && d));
}
static boolean isDigit(char c){
  return c=='0' || c=='1' || c=='2' || c=='3' || c=='4' || c=='5' || c=='6' || c=='7' || c=='8' || c=='9';
}
查看更多
听够珍惜
5楼-- · 2018-12-31 01:52

Java 8 lambda expressions.

String someString = "123123";
boolean isNumeric = someString.chars().allMatch( Character::isDigit );
查看更多
君临天下
6楼-- · 2018-12-31 01:53

Parse it (i.e. with Integer#parseInt ) and simply catch the exception. =)

To clarify: The parseInt function checks if it can parse the number in any case (obviously) and if you want to parse it anyway, you are not going to take any performance hit by actually doing the parsing.

If you would not want to parse it (or parse it very, very rarely) you might wish to do it differently of course.

查看更多
笑指拈花
7楼-- · 2018-12-31 01:56
public static boolean isNumeric(String str)
{
    return str.matches("-?\\d+(.\\d+)?");
}

CraigTP's regular expression (shown above) produces some false positives. E.g. "23y4" will be counted as a number because '.' matches any character not the decimal point.

Also it will reject any number with a leading '+'

An alternative which avoids these two minor problems is

public static boolean isNumeric(String str)
{
    return str.matches("[+-]?\\d*(\\.\\d+)?");
}
查看更多
登录 后发表回答