Convert String to double in Java

1,382,056

Solution 1

You can use Double.parseDouble() to convert a String to a double:

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

For your case it looks like you want:

double total = Double.parseDouble(jlbTotal.getText());
double price = Double.parseDouble(jlbPrice.getText());

Solution 2

If you have problems in parsing string to decimal values, you need to replace "," in the number to "."


String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );

Solution 3

To convert a string back into a double, try the following

String s = "10.1";
Double d = Double.parseDouble(s);

The parseDouble method will achieve the desired effect, and so will the Double.valueOf() method.

Solution 4

double d = Double.parseDouble(aString);

This should convert the string aString into the double d.

Solution 5

Use new BigDecimal(string). This will guarantee proper calculation later.

As a rule of thumb - always use BigDecimal for sensitive calculations like money.

Example:

String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);
Share:
1,382,056
TinyBelly
Author by

TinyBelly

Updated on July 21, 2022

Comments

  • TinyBelly
    TinyBelly almost 2 years

    How can I convert a String such as "12.34" to a double in Java?