The difference in behavior between Double.parseDouble and Integer.parseInt

It seems parseDouble can accept strings with trailing spaces, but parseInt and parseLong throw an exception.

eg. 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"); } } 

results

 works does not work does not work 

Why is there a difference in behavior? Is it intentional?

+5
source share
3 answers

This behavior is really documented (although it's a pretty bad design ...)!

Double.parseDouble :

Returns a new double initialized value represented by the specified string, which is executed by the valueOf method of the Double class.

Double.valueOf :

Leading and trailing whitespace in s are ignored. Spaces are removed as the String.trim () method; that is, both ASCII space and control characters are deleted.

Integer.parseInt :

The characters in the string must be decimal digits , except that the first character can be ASCII minus sign '-' ('\ u002D') to indicate a negative value or ASCII plus sign '+' ('\ u002B') positive value.

+5
source

From source code parseDouble

  in = in.trim(); // don't fool around with white space. 

However, this does not occur in the case of parseInt . They just check for null and continue on.

Agree with you. The authors had to do the same for Integer .

+1
source

Not the same authors who, I believe, are incompatible with the perspective of the Java API. One guy thinks you have to deal with cropping yourself, while another thinks the method can do it for you. I'm not sure which one I prefer, sometimes more strict code (less weak) may be better.

0
source

Source: https://habr.com/ru/post/1275221/


All Articles