8

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?

justAnotherGuy
  • 367
  • 4
  • 10
  • The only answer in the linked duplicate only discusses the implementation of these methods, without even mentioning that this behavior is also documented in [the JavaDocs](https://docs.oracle.com/javase/9/docs/api/java/lang/Double.html#valueOf-java.lang.String-) – Hulk Feb 08 '18 at 05:56
  • Related: https://stackoverflow.com/q/16324831/2513200 – Hulk Feb 08 '18 at 06:15
  • In short, it's history - `Integer.parseInt` existed from the very beginning, `Double.parseDouble` was added in 1.2 according to the JavaDocs. Digging out the reasons behind the decisions would require some Mailing List Archeology, I suppose. They were never changed due to backwards-compatibility considerations. – Hulk Feb 08 '18 at 06:39

3 Answers3

8

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.

Hulk
  • 6,399
  • 1
  • 30
  • 52
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Not the same authors I suppose, thus incoherent from a Java API point of view. One guy thinks you have to deal with trimming yourself, while the other one thinks the method can do it for you. I am not sure which one I prefer, sometimes the stricter code (less lax) can be better.

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85