How can I convert a String
such as \"12.34\"
to a double
in Java?
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);
double d = Double.parseDouble(aString);
This should convert the string aString into the double d.
Using Double.parseDouble()
without surrounding try/catch
block can cause potential NumberFormatException
had the input double string not conforming to a valid format.
Guava offers a utility method for this which returns null
in case your String can't be parsed.
https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html#tryParse(java.lang.String)
Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);
In runtime, a malformed String input yields null
assigned to valueDouble
This is what I would do
public static double convertToDouble(String temp){
String a = temp;
//replace all commas if present with no comma
String s = a.replaceAll(",","").trim();
// if there are any empty spaces also take it out.
String f = s.replaceAll(" ", "");
//now convert the string to double
double result = Double.parseDouble(f);
return result; // return the result
}
For example you input the String "4 55,63. 0 " the output will the double number 45563.0
String s = "12.34";
double num = Double.valueOf(s);
You only need to parse String values using Double
String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);