Java – How to check if a String is numeric
Few Java examples to show you how to check if a String is numeric.
1. Character.isDigit()
Convert a String into a char
array and check it with Character.isDigit()
NumericExample.java
package com.mkyong;
public class NumericExample {
public static void main(String[] args) {
System.out.println(isNumeric("")); // false
System.out.println(isNumeric(" ")); // false
System.out.println(isNumeric(null)); // false
System.out.println(isNumeric("1,200")); // false
System.out.println(isNumeric("1")); // true
System.out.println(isNumeric("200")); // true
System.out.println(isNumeric("3000.00")); // false
}
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
}
Output
false
false
false
false
true
true
false
2. Java 8
This is much simpler now.
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(Character::isDigit);
}
3. Apache Commons Lang
If Apache Commons Lang is present in the claspath, try NumberUtils.isDigits()
pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
import org.apache.commons.lang3.math.NumberUtils;
public static boolean isNumeric(final String str) {
return NumberUtils.isDigits(str);
}
4. NumberFormatException
This solution is working, but not recommend, performance issue.
public static boolean isNumeric(final String str) {
if (str == null || str.length() == 0) {
return false;
}
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Only Integer.parseInt(str) works because in other cases, if there are too many digits, it will return true but Integer.parseInt() will still fail. Also only Integer.parseInt() will work with negative numbers.
{code}
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException(“null”);
}
if (radix Character.MAX_RADIX) {
throw new NumberFormatException(“radix ” + radix +
” greater than Character.MAX_RADIX”);
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
{code}
I didn’t know about Character.isDigit(). I’d normally uses a regex and String.matches (e.g. string.matches(“[0-9]”) or string.matches(“\d”)).
I would like to tweak the isNumeric method to trim the string before processing. The existing code will return false for a string “123456 “.
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
//Remove leading and trailing spaces from a string
str = str.trim();
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
Using regex is faster than Charachter::isDigit. Besides, regex can also return true for floating point numbers like “3000.00”, as well as negative numeric values.
public class NumericExample {
public static void main(String[] args) {
long time1, time2;
time1 = System.currentTimeMillis();
System.out.println(“IsNumeric()”);
System.out.println(isNumeric(“”)); // false
System.out.println(isNumeric(” “)); // false
System.out.println(isNumeric(null)); // false
System.out.println(isNumeric(“1,200”)); // false
System.out.println(isNumeric(“1”)); // true
System.out.println(isNumeric(“200”)); // true
System.out.println(isNumeric(“3000.00”)); // false
time2 = System.currentTimeMillis();
System.out.println(“time: ” + (time2 – time1));
time1 = System.currentTimeMillis();
System.out.println(“\nIsNumericRegex()”);
System.out.println(isNumericRegex(“”)); // false
System.out.println(isNumericRegex(” “)); // false
System.out.println(isNumericRegex(null)); // false
System.out.println(isNumericRegex(“1,200”)); // false
System.out.println(isNumericRegex(“1”)); // true
System.out.println(isNumericRegex(“200”)); // true
System.out.println(isNumericRegex(“3000.00”)); // true
time2 = System.currentTimeMillis();
System.out.println(“time: ” + (time2 – time1));
}
public static boolean isNumeric(final String value) {
if (value == null || value.isEmpty()) {
return false;
}
return value.chars().allMatch(Character::isDigit);
}
public static boolean isNumericRegex(final String value) {
if (value == null || value.isEmpty()) {
return false;
}
return value.matches(“[-+\\d\\.]*”);
}
}