String.format()
Static method จัดรูปแบบ String ตาม Format Specifier คืนค่า String ใหม่
สำหรับ double ใช้ %f (fixed-point) หรือ %e (scientific), %g (general)
ตัวอย่าง
Input จากผู้ใช้
import java.util.Scanner;
public class ConversionOfDouble {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a double value:");
double d = sc.nextDouble();
String result = String.format("%f", d);
System.out.println("The result is: " + result);
}
}
Enter a double value: 2548.2325 The result is: 2548.232500
Hardcoded
public class Sample {
public static void main(String args[]) {
double val = 22588.336;
String str = String.format("%f", val);
System.out.println(str); // 22588.336000
}
}
ควบคุมทศนิยม
String.format("%.2f", val)→ 2 ตำแหน่งทศนิยม (22588.34)String.format("%,.2f", val)→ คั่นพัน + 2 ทศนิยม (22,588.34)
เปรียบเทียบวิธีแปลง double → String
| วิธี | รูปแบบ | ควบคุม Precision | Performance |
|---|---|---|---|
| String.valueOf() | Default | ไม่ได้ | เร็ว |
| Double.toString() | Default | ไม่ได้ | เร็ว |
| StringBuilder.append() | Default | ไม่ได้ | เร็ว (Single-thread) |
| String.format() | Customizable (%f, %.2f, %e) | ได้ | ช้ากว่า (Parsing format) |