Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

แปลงค่า double เป็น String ด้วยเมธอด format ใน Java

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

วิธีรูปแบบควบคุม PrecisionPerformance
String.valueOf()Defaultไม่ได้เร็ว
Double.toString()Defaultไม่ได้เร็ว
StringBuilder.append()Defaultไม่ได้เร็ว (Single-thread)
String.format()Customizable (%f, %.2f, %e)ได้ช้ากว่า (Parsing format)