It seems parseDouble can accept strings with trailing spaces, but parseInt and parseLong throw an Exception.
e.g. For this test case
@Test
public void testNumberParsing() {
try {
Double.parseDouble("123.0 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
try {
Integer.parseInt("123 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
try {
Long.parseLong("123 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
}
The results are
works
does not work
does not work
Why the difference in behaviour? Is that intentional?
valueOf() creates a Double object which is often not needed. parseDouble() does not. With autoboxing it's valueOf(String) which is no longer needed, but is therefore backward compatibility.
parseDouble. Returns a new double initialized to the value represented by the specified String , as performed by the valueOf method of class Double .
Double parseDouble() method in Java with examples The parseDouble() method of Java Double class is a built in method in Java that returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double. Syntax: public static double parseDouble(String s)
If parseInt() is given an empty string or a null value it will also return NaN, rather than converting them to 0. This gives us a mechanism by which we can test values using a combination of parseInt() and isNaN().
This behaviour is actually documented (though this is quite a bad design...)!
Double.parseDouble
:
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
Double.valueOf
:
Leading and trailing whitespace characters in s are ignored. Whitespace is removed as if by the String.trim() method; that is, both ASCII space and control characters are removed.
Integer.parseInt
:
The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
From the source code of parseDouble
in = in.trim(); // don't fool around with white space.
However this is not happening in case of parseInt
. They are simply checking for null
and proceeding further.
Agree with you. Authors should have done the same for Integer as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With