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:43

Here are two methods that might work. (Without using Exceptions). Note : Java is a pass-by-value by default and a String's value is the address of the String's object data. So , when you are doing

stringNumber = stringNumber.replaceAll(" ", "");

You have changed the input value to have no spaces. You can remove that line if you want.

private boolean isValidStringNumber(String stringNumber)
{
    if(stringNumber.isEmpty())
    {
        return false;
    }

    stringNumber = stringNumber.replaceAll(" ", "");

    char [] charNumber = stringNumber.toCharArray();
    for(int i =0 ; i<charNumber.length ;i++)
    {
        if(!Character.isDigit(charNumber[i]))
        {
            return false;
        }
    }
    return true;
}

Here is another method in case you want to allow floats This method allegedly allows numbers in the form to pass 1,123,123,123,123,123.123 i have just made it , and i think it needs further testing to ensure it is working.

private boolean isValidStringTrueNumber(String stringNumber)
{
    if(stringNumber.isEmpty())
    {
        return false;
    }

    stringNumber = stringNumber.replaceAll(" ", "");
    int countOfDecimalPoint = 0;
    boolean decimalPointPassed = false;
    boolean commaFound = false;
    int countOfDigitsBeforeDecimalPoint = 0;
    int countOfDigitsAfterDecimalPoint =0 ;
    int commaCounter=0;
    int countOfDigitsBeforeFirstComma = 0;

    char [] charNumber = stringNumber.toCharArray();
    for(int i =0 ; i<charNumber.length ;i++)
    {
        if((commaCounter>3)||(commaCounter<0))
        {
            return false;
        }
        if(!Character.isDigit(charNumber[i]))//Char is not a digit.
        {
            if(charNumber[i]==',')
            {
                if(decimalPointPassed)
                {
                    return false;
                }
                commaFound = true;
                //check that next three chars are only digits.
                commaCounter +=3;
            }
            else if(charNumber[i]=='.')
            {
                decimalPointPassed = true;
                countOfDecimalPoint++;
            }
            else
            {
                return false;
            }
        }
        else //Char is a digit.
        {
            if ((commaCounter>=0)&&(commaFound))
            {
                if(!decimalPointPassed)
                {
                    commaCounter--;
                }
            }

            if(!commaFound)
            {
                countOfDigitsBeforeFirstComma++;
            }

            if(!decimalPointPassed)
            {
                countOfDigitsBeforeDecimalPoint++;
            }
            else
            {
                countOfDigitsAfterDecimalPoint++;
            }
        }
    }
    if((commaFound)&&(countOfDigitsBeforeFirstComma>3))
    {
        return false;
    }
    if(countOfDecimalPoint>1)
    {
        return false;
    }

    if((decimalPointPassed)&&((countOfDigitsBeforeDecimalPoint==0)||(countOfDigitsAfterDecimalPoint==0)))
    {
        return false;
    }
    return true;
}
查看更多
君临天下
3楼-- · 2018-12-31 01:45

Do not use Exceptions to validate your values. Use Util libs instead like apache NumberUtils:

NumberUtils.isNumber(myStringValue);

Edit:

Please notice that, if your string starts with an 0, NumberUtils will interpret your value as hexadecimal.

NumberUtils.isNumber("07") //true
NumberUtils.isNumber("08") //false
查看更多
梦醉为红颜
4楼-- · 2018-12-31 01:46

A well-performing approach avoiding try-catch and handling negative numbers and scientific notation.

Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)(\\.\\d+)?(E\\d+)?$" );

public static boolean isNumeric( String value ) 
{
    return value != null && PATTERN.matcher( value ).matches();
}
查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 01:47

You can use the java.util.Scanner object.

public static boolean isNumeric(String inputData) {
      Scanner sc = new Scanner(inputData);
      return sc.hasNextInt();
    }
查看更多
泪湿衣
6楼-- · 2018-12-31 01:48
// only int
public static boolean isNumber(int num) 
{
    return (num >= 48 && c <= 57); // 0 - 9
}

// is type of number including . - e E 
public static boolean isNumber(String s) 
{
    boolean isNumber = true;
    for(int i = 0; i < s.length() && isNumber; i++) 
    {
        char c = s.charAt(i);
        isNumber = isNumber & (
            (c >= '0' && c <= '9') || (c == '.') || (c == 'e') || (c == 'E') || (c == '')
        );
    }
    return isInteger;
}

// is type of number 
public static boolean isInteger(String s) 
{
    boolean isInteger = true;
    for(int i = 0; i < s.length() && isInteger; i++) 
    {
        char c = s.charAt(i);
        isInteger = isInteger & ((c >= '0' && c <= '9'));
    }
    return isInteger;
}

public static boolean isNumeric(String s) 
{
    try
    {
        Double.parseDouble(s);
        return true;
    }
    catch (Exception e) 
    {
        return false;
    }
}
查看更多
浅入江南
7楼-- · 2018-12-31 01:48

You can use NumberUtils.isCreatable() from Apache Commons Lang.

Since NumberUtils.isNumber will be deprecated in 4.0, so use NumberUtils.isCreatable() instead.

查看更多
登录 后发表回答