我如何能转换一个字符串,如“12.34”到双在Java?


当前回答

double d = Double.parseDouble(aString);

这将把字符串aString转换为双d。

其他回答

你可以使用double . parsedouble()将String转换为double类型:

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

对于你的案例,它看起来像你想要:

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

再次引用上面Robertiano的引用-因为这是迄今为止最通用和本地化自适应的版本。它值得一个完整的帖子!

另一个选择:

DecimalFormat df = new DecimalFormat(); 
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(','); 
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();

这就是我要做的

    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
}

例如,您输入字符串“4 55,63”。0 " the 输出将双数字45563.0

String s = "12.34";
double num = Double.valueOf(s);
double d = Double.parseDouble(aString);

这将把字符串aString转换为双d。