-3

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,067
  • 10
  • 57
  • 45
Anurag
  • 5
  • 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
  • 12,924
  • 2
  • 19
  • 39
2

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

int a = Integer.parseInt( yourstr.replaceAll("[^0-9]",""));
brso05
  • 12,924
  • 2
  • 19
  • 39
pipedreams2
  • 572
  • 3
  • 22