Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer.parseint in Java, exception when '+' comes first

Tags:

java

Integer.parseInt("-1000"); returns -1000 as the output.

Integer.parseInt("+500"); throws an exception.

How will I be able to recognize positive numbers with the "+" symbol before them without having to trim the symbol?

like image 629
Achilles Avatar asked May 21 '12 13:05

Achilles


2 Answers

Try DecimalFormat like with the pattern "+#;-#". It will handle explicit signed parsing. Breakdown of the pattern:

  • The first part (before ;) is the positive pattern, it has to start with an + char
  • The second part is the negative and has to start with a - char

Example:

DecimalFormat df = new DecimalFormat("+#;-#");
System.out.println(df.parse("+500"));
System.out.println(df.parse("-500"));

Outputs:

500
-500
like image 76
dacwe Avatar answered Nov 10 '22 00:11

dacwe


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.

like image 22
Jon Skeet Avatar answered Nov 09 '22 23:11

Jon Skeet