How to check if a String is numeric in Java ?

Submitted 4 years, 6 months ago
Ticket #255
Views 355
Language/Framework Java
Priority Low
Status Closed

How would you check if a String was a number before parsing it?

Submitted on Oct 19, 20
add a comment

2 Answers

The primary goal - in my mind - to detect one (or more) non numeric character. If there is minimal one then the string cannot be number. The regex would be a perfect possibility for this... The '\D' means in regex one non numeric character. (I am thinking about integers only at the moment, the doubles are an another question.)

It should work in my theory:

System.out.println(Pattern.matches("\\D+", "323abc"));

but it doesn't work in real llife cuz the result is "false"...

Similar in Perl is perfect:

perl -e "print 1 if (\"45v543\" =~ /\D/)"

Result: 1

Submitted 4 years, 6 months ago

Can anyone explain, that the Pattern.matches why doesn't work...?

- kijato 4 years, 6 months ago


Verified

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)

Submitted 4 years, 6 months ago


Latest Blogs