HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How to check if a String is numeric in Java

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howjavachecknumericstring

Problem

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

Solution

With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.

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

Context

Stack Overflow Q#1102891, score: 797

Revisions (0)

No revisions yet.