當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Double toString()用法及代碼示例

用法:

    public String toString();
    public static String toString(double value);

Double類toString()方法

  • toString() 方法可在java.lang包。
  • toString() 方法用於獲取 Double 值/對象的字符串值(用 "this" 對象調用)。
  • toString(double value) 方法也用於獲取給定雙精度值的字符串值(這裏,我們將雙精度值/對象作為參數傳遞)。
  • 兩種類型的方法在從 Double 轉換為 String 時都不會拋出異常。
  • 這兩種類型的方法都是非靜態方法,隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,則會出現錯誤。

參數:

  • 第一種情況:toString(),我們不傳遞任何參數或值。
  • 第二種情況:toString(double value),我們隻傳遞一個參數doubletype 它代表要轉換的雙精度值。

返回值:

在第一種情況下, String– 它返回此 Double 對象的字符串表示形式。

在第二種情況下, String– 它返回給定參數的字符串表示是雙精度類型。

例:

// Java program to demonstrate the example 
// of toString () method of Double class

public class ToStringOfDoubleClass {
    public static void main(String[] args) {
        // Object initialization
        Double ob1 = new Double("10.20");
        Double ob2 = new Double("20.20");

        // Display ob1,ob2 values
        System.out.println("ob1:" + ob1);
        System.out.println("ob2:" + ob2);

        // It represents string of this Double object
        String value1 = ob1.toString();

        // It represents string of the given double parameter
        String value2 = Double.toString(ob2);

        // Display result values
        System.out.println("ob1.toString():" + value1);
        System.out.println("Double.toString(ob2):" + value2);
    }
}

輸出

ob1:10.2
ob2:20.2
ob1.toString():10.2
Double.toString(ob2):20.2


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java Double class toString() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。