How to parse a string containing the character "+"

I have a line with numbers.

I have a code like this

String tempStr = "+123"; NumberFormat numformat = NumberFormat.getNumberInstance(); numformat.setParseIntegerOnly(true); try { int ageInDays = Integer.parseInt(tempStr); System.out.println("the age in days "+ageInDays); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

It works great for numbers with negative characters. But I can’t do this for the number with the β€œ+” symbol. It throws a NumberFormatException.

So, how can I parse a number with a β€œ+” character from a string?

+6
source share
2 answers

If using Java 7 or higher, I would recommend using java.lang.Long; or java.lang.Integer; (if you are sure that you have to parse integers).

It works for both cases.

Edit further: I have not seen that you are using Integer.parseInt ();

Therefore, I assume that you have Java 6 or less.

In this case, try calling the following method before the line with Integer.parseInt(tempStr); to remove + if it exists:

 private static String removePlusSignIfExists(String numberAsString) { if(numberAsString == null || numberAsString.length() == 0){ return numberAsString; } if(numberAsString.charAt(0) == '+'){ return numberAsString.substring(1, numberAsString.length()); } else { return numberAsString; } } 
+4
source

This function basically replaces "+" with " an empty string, so " + 12 + 3 " will return 123 .

 public int parseInt(String text) { return Integer.parseInt(text.replaceAll("+", "")); } 

An example of using this is

 System.out.println(parseInt("+123")); //Returns 123 

I hope this helps!

+2
source

All Articles