Integer.parseInt(\"-1000\");
returns -1000 as the output.
Integer.parseInt(\"+500\");
throws an exception.
How will I be able to re
Try DecimalFormat like with the pattern "+#;-#"
. It will handle explicit signed parsing. Breakdown of the pattern:
;
) is the positive pattern, it has to start with an +
char-
charExample:
DecimalFormat df = new DecimalFormat("+#;-#");
System.out.println(df.parse("+500"));
System.out.println(df.parse("-500"));
Outputs:
500
-500
The implementation has changed from java 6 to 7. Intger.parseInt("+500") used to Exception till java 6 , but works perfectly fine with java 7
One option is to use Java 7... assuming that behaves as documented:
Parses the string argument as a signed decimal integer. 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.
It looks like this was a new feature introduced into Java 7 though. The JDK 6 docs only indicate that -
is handled.
The method is behaving as described in the documentation:
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.
You need to skip the first character if it is a +
to do the parse correctly:
if (s.charAt(0) == '+') s = s.substring(1);
int val= Integer.parseInt(s);
public static int parseInt(String s) throws NumberFormatException
Parses the string argument as a signed decimal integer. 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. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
Javadoc
I am using Java 7, and Integer.parseInt("+500");
is not throwing any exception.
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 7 documentation for Integer.parseInt(String)