Convert String to double in Java

2018-12-31 09:55发布

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

12条回答
何处买醉
2楼-- · 2018-12-31 10:21
double d = Double.parseDouble(aString);

This should convert the string aString into the double d.

查看更多
时光乱了年华
3楼-- · 2018-12-31 10:21
String double_string = "100.215";
Double double = Double.parseDouble(double_string);
查看更多
像晚风撩人
4楼-- · 2018-12-31 10:22

You only need to parse String values using Double

String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);
查看更多
与风俱净
5楼-- · 2018-12-31 10:25

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);
查看更多
旧人旧事旧时光
6楼-- · 2018-12-31 10:28

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

查看更多
美炸的是我
7楼-- · 2018-12-31 10:30

There is another way too.

Double temp = Double.valueOf(str);
number = temp.doubleValue();

Double is a class and "temp" is a variable. "number" is the final number you are looking for.

查看更多
登录 后发表回答