Advertisement
Advertisement


Convert String to double in Java


Question

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

2017/12/30
1
290
12/30/2017 7:48:44 PM


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(",",".") );
2014/10/25

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.

2017/05/09

double d = Double.parseDouble(aString);

This should convert the string aString into the double d.


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);
2011/04/24

You only need to parse String values using Double

String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);
2014/03/22

Source: https://stackoverflow.com/questions/5769669
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]