This example will show how to check if a string is number in java by using Double parseDouble, NumberFormat, Character.isDigit, a regex, guava and apache commons.
Straight up Java Is number w/parseDouble @Test
public void is_string_a_number_java () {
boolean isANumber = false ;
String numberString = "1234.54" ;
try {
Double . parseDouble ( numberString );
isANumber = true ;
} catch ( NumberFormatException nfe ) {
// do nothing
}
assertTrue ( isANumber );
}
@Test
public void is_string_a_number_numberformat_java () {
boolean isANumber = true ;
String numberString = "1234.54" ;
try {
NumberFormat . getInstance (). parse ( numberString );
} catch ( ParseException nfe ) {
isANumber = false ;
}
assertTrue ( isANumber );
}
Is number w/char array @Test
public void is_string_a_number_java_with_char_array () {
boolean isANumber = true ;
String numberString = "1234" ;
for ( char c : numberString . toCharArray ()) {
if (! Character . isDigit ( c )) {
isANumber = false ;
}
}
assertTrue ( isANumber );
}
Is number w/ regex @Test
public void is_string_a_number_java_with_regular_expression () {
boolean isANumber = false ;
String numberString = "1234.54" ;
if ( numberString . matches ( "[+-]?\d*(\.\d+)?" )) {
isANumber = true ;
}
assertTrue ( isANumber );
}
Google Guava @Test
public void is_string_a_number_guava () {
Double parsedString = Doubles . tryParse ( "123234.54" );
assertEquals ( new Double ( 123234.54 ), parsedString );
}
Apache Commons Is number w/StringUtils @Test
public void is_string_a_number_apache_commons_stringutils () {
boolean isANumber = StringUtils . isNumeric ( "12345" );
assertTrue ( isANumber );
}
String isNumber @Test
public void is_string_a_number_apache_commons () {
boolean isANumber = NumberUtils . isNumber ( "12345" );
assertTrue ( isANumber );
}
@Test
public void is_formatted_string_a_number_apache_commons () {
boolean isANumber = NumberUtils . isNumber ( "123123.45" );
assertTrue ( isANumber );
}
Is string numeric posted by Justin Musgrove on 07 October 2013
Tagged: java and java-number
Share on: Facebook Google+
All the code on this page is available on github:
IsStringANumber.java