The below example shows how to verify that a string contains only numeric values in Java. String may contain float value, double value etc. This example uses regular expression to check a string contains only numeric values. This method will not throw any exception.
Below is the method which validates a string contains only numeric values.

public static boolean isStringNumeric(String str) {
    final String Digits = "(\\p{Digit}+)";
    final String HexDigits = "(\\p{XDigit}+)";
    final String Exp = "[eE][+-]?" + Digits;
    final String fpRegex = ("[\\0-\\x20]*[+-]?(NaN|Infinity|(((" + Digits
            + "(\\.)?(" + Digits + "?)(" + Exp + ")?)|(\\.(" + Digits
            + ")(" + Exp + ")?)|(((0[xX]" + HexDigits + "(\\.)?)|(0[xX]"
            + HexDigits + "?(\\.)" + HexDigits + ")" + ")[pP][+-]?"
            + Digits + "))[fFdD]?))[\\0-\\x20]*");
    if (Pattern.matches(fpRegex, str)) {
        return false;
    }
    return true;
}

 

Below is the test method which gives the expected result from the above method.

public static void main(String[] args) {
    System.out.println("abc: " + isStringNumeric("abc"));
    System.out.println("abc125: " + isStringNumeric("abc125"));
    System.out.println("abc125.25: " + isStringNumeric("abc125.25"));
    System.out.println("125.25d: " + isStringNumeric("125.25d"));
    System.out.println("125d: " + isStringNumeric("125d"));
    System.out.println("125f: " + isStringNumeric("125f"));
    System.out.println("125.00: " + isStringNumeric("125.00"));
    System.out.println("125: " + isStringNumeric("125"));
}

 

Output

abc: false
abc125: false
abc125.25: false
125.25d: true
125d: true
125f: true
125.00: true
125: true

 

Thanks for reading. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *