Check Valid Number In Java String

Sometimes we need to check whether the user input is a valid number or not. If not, we need to tell the user to input a valid number again. In this example, we will show you two methods about how to verify a valid numeric value in a Java String variable.

1. Use Double.parseDouble() and Integer.parseInt().

/* Use Double and Integer parse method to check. */
private static boolean ifValidNumber(String str)
	boolean ret = true;
			str = str.trim();
			int dotIndex = str.indexOf(".");
			/* If contain dot, then it should be a double number.*/
				/*If not contain dot, then it should be a integer String. */
	}catch(NumberFormatException ex)
		/* If parse String method throw a NumberFormatException, then it is not a String. */
		ret = false;
	return ret;

2. Use Apache Commons Lang StringUtils.

  1. Go to Apache Commons Lang Project Home Page.
  2. Click the Download link in the left panel.
  3. Download the latest stable version of Apache Commons Lang on the download page.
  4. Extract the download zip file into a local folder, such as C:/WorkSpace/
  5. Add the commons-lang3-3.6.jar file into your java project’s build path. Right-click the java project, click ” Build Path —> Configure Build Path “.
  6. Click the ” Add External JARS ” button in the popup dialog.
  7. Browse to the extracted zip file folder, select commons-lang3-3.6.jar. Click OK to add it.
  8. Now you can use the below java code to implement this function.
    /* Use Apache Commons Lang project StringUtils to check. */
    private static boolean ifValidNumberByApacheCommonsLang(String strNum)
    	boolean ret = StringUtils.isNumeric(strNum);
    	return ret;

3. Java Main Method.

public static void main(String[] args) {
	String strArr[] = {"123", "12.3", "123df56", "abcde", "[email protected]"};
	for(String strNum : strArr)
		//boolean isValidNumber = CheckValidNumberInJavaString.ifValidNumber(strNum);
		boolean isValidNumber = CheckValidNumberInJavaString.ifValidNumberByApacheCommonsLang(strNum);
			System.out.println(strNum + " is a valid number");
			System.out.println(strNum + " is not a valid number");

0 0 votes
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x