0

we are checking integer and float both type of numbers are valid or not. if dataValue containing some string then it will return true.

public boolean isValidNumber(String dataValue)
{

    // check the string for null and empty
    if (dataValue == null || (dataValue != null && dataValue.trim().equals(""))) return false;

    // traverse the string and check each character
    boolean isValidNumber = true;
    for (int i = 0; i < dataValue.length(); i++)
    {
        if(dataValue.charAt(i) == '.') continue;
        if ((dataValue.charAt(i) < '0') || (dataValue.charAt(i) > '9'))
        {
            isValidNumber = false;

            break;
        }
    }

    return (isValidNumber);
}

my question is, Is it right approach to check number is valid or not.

Vinay Sharma
  • 1,163
  • 1
  • 10
  • 20
  • you can try parsing the string to a float, if an exception is raised the string is not a valid number – Fran Montero May 20 '15 at 12:35
  • Use [regex](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) instead – kaykay May 20 '15 at 12:36
  • A very weird definition of "valid number". Also: As many `.` as you like? – fabian May 20 '15 at 12:42
  • I guess you should rename your method to `isNotValidNumber`. Everytime you return `true` you found a reason why the passed String is has not a valid number. – Tom May 20 '15 at 13:05

0 Answers0