Convert String to double in Java

后端 未结 14 1480
傲寒
傲寒 2020-11-22 05:52

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

相关标签:
14条回答
  • 2020-11-22 06:13

    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);
    
    0 讨论(0)
  • 2020-11-22 06:15
    double d = Double.parseDouble(aString);
    

    This should convert the string aString into the double d.

    0 讨论(0)
  • 2020-11-22 06:15

    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

    0 讨论(0)
  • 2020-11-22 06:17

    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

    0 讨论(0)
  • 2020-11-22 06:19
    String s = "12.34";
    double num = Double.valueOf(s);
    
    0 讨论(0)
  • 2020-11-22 06:26

    You only need to parse String values using Double

    String someValue= "52.23";
    Double doubleVal = Double.parseDouble(someValue);
    System.out.println(doubleVal);
    
    0 讨论(0)
提交回复
热议问题