Java - Double valueOf(String) 方法



描述

Java Double valueOf(String s) 方法返回一個包含引數字串 s 所表示的雙精度數值的 Double 物件。如果 s 為 null,則丟擲 NullPointerException

宣告

以下是 java.lang.Double.valueOf() 方法的宣告

public static Double valueOf(String s) throws NumberFormatException

引數

s − 要解析的字串。

返回值

此方法返回一個包含 String 引數表示的值的 Double 物件。

異常

NumberFormatException − 如果字串不包含可解析的數字。

從字串獲取 Double 示例

以下示例演示瞭如何使用 Double valueOf(String) 方法從字串獲取 Double 物件。我們建立了一個包含有效雙精度值的字串,然後使用 valueOf() 方法檢索 Double 物件並列印它。

package com.tutorialspoint;
public class DoubleDemo {
   public static void main(String[] args) {

      // returns the double value represented by the string argument
      String str = "50";
      Double retval = Double.valueOf(str);
      System.out.println("Value = " + retval);
   }
}  

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Value = 50.0

從無效字串獲取 Double 時遇到異常示例

以下示例演示瞭如何使用 Double valueOf(String) 方法從字串獲取 Double 物件。我們建立了一個包含無效雙精度值的字串,然後使用 valueOf() 方法嘗試檢索 Double 物件並列印它。程式按預期丟擲異常。

package com.tutorialspoint;
public class DoubleDemo {
   public static void main(String[] args) {

      // returns the double value represented by the string argument
      String str = "abc";
      Double retval = Double.valueOf(str);
      System.out.println("Value = " + retval);
   }
}  

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
	at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
	at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
	at java.lang.Double.parseDouble(Unknown Source)
	at java.lang.Double.valueOf(Unknown Source)
	at com.tutorialspoint.DoubleDemo.main(DoubleDemo.java:9)

從負數字符串獲取 Double 示例

以下示例演示瞭如何使用 Double valueOf(String) 方法從字串獲取 Double 物件。我們建立了一個包含有效負雙精度值的字串,然後使用 valueOf() 方法檢索 Double 物件並列印它。

package com.tutorialspoint;
public class DoubleDemo {
   public static void main(String[] args) {

      // returns the double value represented by the string argument
      String str = "-50";
      Double retval = Double.valueOf(str);
      System.out.println("Value = " + retval);
   }
}  

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Value = -50.0
java_lang_double.htm
廣告
© . All rights reserved.