Verify a string contains only numeric value in Java

Introduction

The below example shows how to verify that a string contains only numeric value in Java. String may contain float value, double value etc. This example uses regular expression to check a string contains only numeric values. It makes sure that your string should contain only digits and dot(.).

You may need sometimes to use string variable for storing numeric data. As the variable is string type, so by mistake your string variable may contain non-numeric values which are not correct values for processing further business logic. Therefore you need to verify the value in string before processing it for your business requirements.

Prerequisites

Java 1.8

Example with Source Code

Here we will create a method for validating a given string for numeric values and this method will not throw any exception if validation fails.

Creating Validation Method

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 Expression = "[eE][+-]?" + Digits;
	final String numericRegex = "[\\x00-\\x20]*[+-]?(NaN|Infinity|(((" + Digits + "(\\.)?(" + Digits + "?)("
			+ Expression + ")?)|(\\.(" + Digits + ")(" + Expression + ")?)|(((0[xX]" + HexDigits + "(\\.)?)|(0[xX]"
			+ HexDigits + "?(\\.)" + HexDigits + ")" + ")[pP][+-]?" + Digits + "))[fFdD]?))[\\x00-\\x20]*";
	final Pattern NUMBER_PATTERN = Pattern.compile(numericRegex);
	return NUMBER_PATTERN.matcher(str).matches();
}

Creating Main Method

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"));
}

Testing

Output

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

That’s all.

Source Code

Download Source Code

Thanks for reading.

Related posts

Leave a Comment