0

I'm writing a program that is dealing with about 150 different variables, which I have extracted off a webpage. I was looking at how to change them into a double variable, so that I can compare them later in the program, and found this code to do so:

String text = "12.34"; // example String
double value = Double.parseDouble(text);

This works fine for some of them, but a lot of the numbers that I'm extracting from the webpage as a String variable come in the form '1,200.000', with the comma (,) to separate the number into thousands.

As a result, the program will not allow me to run the above code on them, because of that comma (,). How do I get rid of the comma, and hence change these Strings, like 1,200.000, into a double variable, like 1200.000?

Eran
  • 387,369
  • 54
  • 702
  • 768
user296950
  • 35
  • 1
  • 8
  • 3
    You need locale aware parsing. See http://stackoverflow.com/questions/888088/how-do-i-convert-a-string-to-double-in-java-using-a-specific-locale – Jayan Nov 15 '14 at 11:53

2 Answers2

2

You can easily get rid of the comma :

double value = Double.parseDouble(text.replace(",",""));

Note that this will only work if comma's are used for the thousand separator. Other locales may switch the command and dot around.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Will I be able to use that even if some of the numbers do not have commas, or will it return an error? – user296950 Nov 15 '14 at 11:56
  • @Eran In French (and most of EU if I'm not mistaken) the thousand separator and the decimal separator are switched. – Maarten Bodewes Nov 15 '14 at 12:07
  • @owlstead What makes you think the OP cares about French locale? They only asked about getting rid of the comma. – Eran Nov 15 '14 at 12:09
0

First just delete the commas from the String and then parse it into Double:

String text = text.replace(",", "");
double val = Double.parseDouble(text);

Note that this will only work if comma's are used for the thousand separator. Other locales may switch the command and dot around.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Jilberta
  • 2,836
  • 5
  • 30
  • 44