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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Will I be able to use that even if some of the numbers do not have commas, or will it return an error?
@Eran In French (and most of EU if I'm not mistaken) the thousand separator and the decimal separator are switched.
@owlstead What makes you think the OP cares about French locale? They only asked about getting rid of the comma.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.