Reputation: 3297
I'm getting NumberFormatException
when I try to parse 265,858 with Integer.parseInt()
.
Is there any way to parse it into an integer?
Upvotes: 45
Views: 102175
Reputation: 340763
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.
Upvotes: 86
Reputation: 6754
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
}
Upvotes: 13
Reputation: 25136
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)
Upvotes: 2
Reputation: 14363
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);
Upvotes: 4
Reputation: 49582
You can remove the ,
before parsing it to an int:
int i = Integer.parseInt(myNumberString.replaceAll(",", ""));
Upvotes: 22
Reputation: 4516
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)));
Upvotes: 0
Reputation: 20442
One option would be to strip the commas:
"265,858".replaceAll(",","");
Upvotes: 5