Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse number string containing commas into an integer in java?

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

Is there any way to parse it into an integer?

like image 555
vivek_jonam Avatar asked Aug 15 '12 16:08

vivek_jonam


People also ask

How do you convert a string to int with a comma?

To parse a string with commas to a number:Use the replace() method to remove all the commas from the string. The replace method will return a new string containing no commas. Convert the string to a number.

How do you remove commas from numbers in Java?

You can use String's replace() or replaceAll() method to remove comma from number in java.


1 Answers

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.

like image 155
Tomasz Nurkiewicz Avatar answered Sep 21 '22 18:09

Tomasz Nurkiewicz