似乎 parseDouble 可以接受带有尾随空格的字符串,但 parseInt 和 parseLong 会抛出异常。
例如对于这个测试用例
@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");
}
}
结果是
works
does not work
does not work
为什么会有不同的行为?这是故意的吗?
最佳答案
这种行为实际上已被记录(尽管这是一个非常糟糕的设计......)!
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
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.
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.
关于java - Double.parseDouble 和 Integer.parseInt 之间的行为差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48669698/