StringUtils
java class in Apache commons library provides a method isNumeric
to check if given sequence of characters contains digits only. But this is not a sure shot way to check for numbers because for a string containing decimal the StringUtils.isNumeric
returns false as shown below:
String number = "123";
System.out.println("123 is number? " + StringUtils.isNumeric(number));
//123 is number? true
String decimalNumber = "123.0";
System.out.println("123.0 is number? " + StringUtils.isNumeric(decimalNumber));
//123.0 is number? false
A better approach is to use NumberUtils.isCreatable
which adopts a more exhaustive approach to check for numericity of a string as shown below:
System.out.println("123 is number? " + NumberUtils.isCreatable(number));
//123 is number? true
System.out.println("123.0 is number? " + NumberUtils.isCreatable(decimalNumber));
//123.0 is number? true
The same class provides an API createNumber
to convert the String
into a Number
as shown below:
Number decimalNumObj = NumberUtils.createNumber("123.47");
We can then get any desired numeric datatype value from this Number
object using its methods like longValue()
, doubleValue()
, intValue()
, shortValue()
.
The post Gotcha: Using Apache Commons StringUtils.isNumeric appeared first on Experiences Unlimited.