-2

I am trying to convert a String to an Integer value.

example : "3,879" to 3879.

How to do that using java.text.Numberformat; or If there is any other way to do that.

Thanks in advance.

Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45
Anurag
  • 15
  • 3

2 Answers2

2

You could do something like this:

String myNumber = "3,359";
myNumber = myNumber.replaceAll(",", "");
int test = Integer.parseInt(myNumber);
System.out.println("" + test);

You can do it like this also:

link for number formatpackage

This answer uses code from above link:

NumberFormat.getNumberInstance(java.util.Locale.US).parse("265,858");

int test = 0;
try {
    test = NumberFormat.getNumberInstance(java.util.Locale.US).parse("265,858").intValue();
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("" + test);
Community
  • 1
  • 1
brso05
  • 13,142
  • 2
  • 21
  • 40
2

You can strip the commas with replaceAll from the string and use parseInt.

int a = Integer.parseInt( yourstr.replaceAll("[^0-9]",""));
brso05
  • 13,142
  • 2
  • 21
  • 40
pipedreams2
  • 602
  • 5
  • 24