The standard way to do this would be:
double d;
try {
d = Double.parseDouble(input);
}
catch (NumberFormatException e) {
// Use whatever default you like
d = -1.0;
}
This can of course be wrapped up as a library method if you like.
On the whole I don't miss this not being part of the language - if a string is badly formed, it doesn't represent -1
so the correct thing to do is throw an exception. If you want to treat this as -1
you're free to do so, but there's very weak rationale to make this standard library behaviour (why -1
and not 0
or NaN
or null
?).