How to parse number string containing commas into an integer in java?
Solution 1:
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.
Solution 2:
You can remove the ,
before parsing it to an int:
int i = Integer.parseInt(myNumberString.replaceAll(",", ""));
Solution 3:
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
}