Verify a string contains only numeric value in Java

You may also like to read:

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(.).

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

Source Code

You can download source code.

Thanks for reading.

Verify a string contains only numeric value in Java

Leave a Reply

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

Scroll to top