简体   繁体   中英

JAVA: How do you convert a String variable to a Double variable?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM