簡體   English   中英

在Java中將String轉換為double

[英]Convert String to double in Java

如何在 Java 中將諸如"12.34"類的String轉換為double "12.34"

您可以使用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());

如果在將字符串解析為十進制值時遇到問題,則需要將數字中的“,”替換為“.”。


String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );

要將字符串轉換回雙精度,請嘗試以下操作

String s = "10.1";
Double d = Double.parseDouble(s);

parseDouble 方法將達到預期的效果,Double.valueOf() 方法也是如此。

double d = Double.parseDouble(aString);

這應該將字符串 aString 轉換為雙精度 d。

使用new BigDecimal(string) 這將保證以后正確計算。

根據經驗 - 始終使用BigDecimal進行敏感計算,例如金錢。

例子:

String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);

您只需要使用 Double 解析字符串值

String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);

再次引用上面 Robertiano 的話——因為這是迄今為止最通用和本地化自適應的版本。 它值得一個完整的帖子!

另外一個選擇:

DecimalFormat df = new DecimalFormat(); 
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(','); 
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();
String double_string = "100.215";
Double double = Double.parseDouble(double_string);

還有另一種方式。

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

Double 是一個類,而“temp”是一個變量。 “數字”是您要查找的最終數字。

這就是我會做的

    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 " 輸出將是雙數 45563.0

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

使用Double.parseDouble()而不包圍try/catch塊可能會導致潛在的NumberFormatException輸入雙字符串不符合有效格式。

Guava 為此提供了一個實用方法,如果您的 String 無法解析,它會返回null

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);

在運行時,格式錯誤的字符串輸入產生分配給valueDouble null

當您需要 int 時,使用它來將任何 String 數字轉換為 double 只需將數據類型從 num 和 num2 轉換為 int ; 使用 Eng 處理任何字符串 double 的所有情況:“Bader Qandeel”

public static double str2doubel(String str) {
    double num = 0;
    double num2 = 0;
    int idForDot = str.indexOf('.');
    boolean isNeg = false;
    String st;
    int start = 0;
    int end = str.length();

    if (idForDot != -1) {
        st = str.substring(0, idForDot);
        for (int i = str.length() - 1; i >= idForDot + 1; i--) {
            num2 = (num2 + str.charAt(i) - '0') / 10;
        }
    } else {
        st = str;
    }

    if (st.charAt(0) == '-') {
        isNeg = true;
        start++;
    } else if (st.charAt(0) == '+') {
        start++;
    }

    for (int i = start; i < st.length(); i++) {
        if (st.charAt(i) == ',') {
            continue;
        }
        num *= 10;
        num += st.charAt(i) - '0';
    }

    num = num + num2;
    if (isNeg) {
        num = -1 * num;
    }
    return num;
}

試試這個,BigDecimal bdVal = new BigDecimal(str);

如果你只想要 Double 那就試試 Double d = Double.valueOf(str); System.out.println(String.format("%.3f", new BigDecimal(d)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM