How to check if a String is numeric in Java

在解析它之前,你会如何检查一个String是否是一个数字?


With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric .

With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric .

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. (The linked javadocs contain detailed examples for each method.)


This is generally done with a simple user-defined function (ie Roll-your-own "isNumeric" function).

Something like:

public static boolean isNumeric(String str)  
{  
  try  
  {  
    double d = Double.parseDouble(str);  
  }  
  catch(NumberFormatException nfe)  
  {  
    return false;  
  }  
  return true;  
}

However, if you're calling this function a lot, and you expect many of the checks to fail due to not being a number then performance of this mechanism will not be great, since you're relying upon exceptions being thrown for each failure, which is a fairly expensive operation.

An alternative approach may be to use a regular expression to check for validity of being a number:

public static boolean isNumeric(String str)
{
  return str.matches("-?d+(.d+)?");  //match a number with optional '-' and decimal.
}

Be careful with the above RegEx mechanism, though, as it will fail if you're using non-Arabic digits (ie numerals other than 0 through to 9). This is because the "d" part of the RegEx will only match [0-9] and effectively isn't internationally numerically aware. (Thanks to OregonGhost for pointing this out!)

Or even another alternative is to use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric:

public static boolean isNumeric(String str)
{
  NumberFormat formatter = NumberFormat.getInstance();
  ParsePosition pos = new ParsePosition(0);
  formatter.parse(str, pos);
  return str.length() == pos.getIndex();
}

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

链接地址: http://www.djcxy.com/p/3550.html

上一篇: java中parseInt和valueOf之间的区别?

下一篇: 如何在Java中检查字符串是否为数字