什麼是「雙」?
Java 中的基本資料類型「double」用於儲存精度更高的十進位數,最高可達 15 位數。雖然“float”提供 6-7 位元精度,但“double”更廣泛地用於更高精度的計算和測量。
Java 中的「Double」是什麼?
「Double」是Java中的包裝類,用於儲存「double」的原始類型。它附帶了一系列用於“雙重”操作和計算的有用函數。例如,您可以使用其包裝物件非常有效地將 Java double 轉換為字串。如何將 Java Double 轉換為 String?
在Java中可以透過各種簡單的方法將雙精度數轉換為字串。讓我們來看幾個例子。Double.toString() 方法
package com.doubletostring.java;
public class ConvertDoubleToString {
public static void main(String[] args) {
Double pi = 3.141592653589793;
System.out.println("Pi Double: " + pi);
// Converting Double to String using Double.toString() method
String piStr = Double.toString(pi);
System.out.println("Pi String: " + piStr);
}
}
輸出
Pi 雙值:3.141592653589793 Pi 字串:3.141592653589793
這是將 Java 雙精度數轉換為字串的最方便且最常用的方法。
String.valueOf() 方法
package com.doubletostring.java;
public class StringValueOfDouble {
public static void main(String[] args) {
Double screwGaugeReading = 7.271572353580126;
System.out.println("Screw Gauge Reading Double: " + screwGaugeReading);
// Converting Double to String using String.valueOf() method
String screwGaugeReadingStr = String.valueOf(screwGaugeReading);
System.out.println("Screw Gauge Reading String: " + screwGaugeReadingStr);
}
}
輸出
螺絲規讀數雙:7.271572353580126 螺絲規讀數字串:7.271572353580126
String.format() 方法
package com.doubletostring.java;
public class StringFormat {
public static void main(String[] args) {
Double vernierCalliper = 7.271572353580126;
System.out.println("Vernier Calliper Double: " + vernierCalliper);
// Converting Double to String using String.format() method
// Format Literal "%s" returns String for any parameter data type
// Parameter is "Double" in our case
String vernierCalliperStr = String.format("%s", vernierCalliper);
System.out.println("Vernier Calliper String: " + vernierCalliperStr);
}
}
輸出
雙遊標卡尺:7.271572353580126 串遊標卡尺:7.271572353580126
GO TO FULL VERSION