44

I'm getting NumberFormatException when I try to parse 265,858 with Integer.parseInt().

Is there any way to parse it into an integer?

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
vivek_jonam
  • 3,237
  • 8
  • 32
  • 44

7 Answers7

85

Is this comma a decimal separator or are these two numbers? In the first case you must provide Locale to NumberFormat class that uses comma as decimal separator:

NumberFormat.getNumberInstance(Locale.FRANCE).parse("265,858")

This results in 265.858. But using US locale you'll get 265858:

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

That's because in France they treat comma as decimal separator while in US - as grouping (thousand) separator.

If these are two numbers - String.split() them and parse two separate strings independently.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
22

You can remove the , before parsing it to an int:

int i = Integer.parseInt(myNumberString.replaceAll(",", ""));
micha
  • 47,774
  • 16
  • 73
  • 80
  • Take note that `replaceAll` is used, critical for any number `>999,999`. This also removes the need to throw/catch the checked exception from other answers. – Graham Russell May 10 '18 at 20:21
13

If it is one number & you want to remove separators, NumberFormat will return a number to you. Just make sure to use the correct Locale when using the getNumberInstance method.

For instance, some Locales swap the comma and decimal point to what you may be used to.

Then just use the intValue method to return an integer. You'll have to wrap the whole thing in a try/catch block though, to account for Parse Exceptions.

try {
    NumberFormat ukFormat = NumberFormat.getNumberInstance(Locale.UK);
    ukFormat.parse("265,858").intValue();
} catch(ParseException e) {
    //Handle exception
}
anotherdave
  • 6,656
  • 4
  • 34
  • 65
5

One option would be to strip the commas:

"265,858".replaceAll(",","");
Tim Bender
  • 20,112
  • 2
  • 49
  • 58
4

The first thing which clicks to me, assuming this is a single number, is...

String number = "265,858";
number.replaceAll(",","");
Integer num = Integer.parseInt(number);
Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
2

Or you could use NumberFormat.parse, setting it to be integer only.

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html#parse(java.lang.String)

John Gardner
  • 24,225
  • 5
  • 58
  • 76
0

Try this:

String x = "265,858 ";
    x = x.split(",")[0];
    System.out.println(Integer.parseInt(x));

EDIT : if you want it rounded to the nearest Integer :

    String x = "265,858 ";
    x = x.replaceAll(",",".");
    System.out.println(Math.round(Double.parseDouble(x)));
SpiXel
  • 4,338
  • 1
  • 29
  • 45