I want to know if a string is a double or not
for example
value1 = "236.685"
value2 = "it is 3"
I want a code which will return
value1
is a double
value2
is not a double
for example
value1 = "236.685"
value2 = "it is 3"
I want a code which will return
value1
is a double
value2
is not a double
You can check that by trying to parse the string with Double.parseDouble()
and catching a NumberFormatException
. If it doesn't throw this exception, it's a valid double. This code:
private static boolean isDouble(String string)
{
try
{
Double.parseDouble(string);
}
catch (NumberFormatException e)
{
return false;
}
return true;
}
public static void main(String[] args)
{
String maybeDouble0 = "123.4";
String maybeDouble1 = "not a double 345";
String maybeDouble2 = "45";
String maybeDouble3 = "321.";
String maybeDouble4 = ".753";
String maybeDouble5 = "just text";
System.out.println(maybeDouble0 + ": " + isDouble(maybeDouble0));
System.out.println(maybeDouble1 + ": " + isDouble(maybeDouble1));
System.out.println(maybeDouble2 + ": " + isDouble(maybeDouble2));
System.out.println(maybeDouble3 + ": " + isDouble(maybeDouble3));
System.out.println(maybeDouble4 + ": " + isDouble(maybeDouble4));
System.out.println(maybeDouble5 + ": " + isDouble(maybeDouble5));
}
will result in this output:
123.4: true
not a double 345: false
45: true
321.: true
.753: true
just text: false
I prefer this method over a RegEx pattern because it's asking Java directly, instead of assuming to know Java's internal double representations.
Use a try catch statement for Double.parseDouble()
try{
double num = Double.parseDouble(value);
System.out.println("is a double");
catch (Exception e){
System.out.println("not a double");
}
You can use a combination of parseInt and parseDouble
The reason you need both is because parseDouble will still parse ints. You can probably combine them, I just wrote two separate functions, one checks ints and the other checks double.
If isInt is false and isDouble is true then it is a double
If both are true, then it is an int(i think that is not a double from your example). If both are false then its not a number.
The last case is never possible.
public static boolean isInt( String str ){
try{
Integer.parseInt( str );
System.out.println("true");
return true;
}catch( Exception e ){
System.out.println("false");
return false;
}
}
public static boolean isDouble( String str ){
try{
Double.parseDouble( str );
System.out.println("true");
return true;
}catch( Exception e ){
System.out.println("false");
return false;
}
}