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

วิธีแปลง double เป็น string ใน C++

ภาพรวม

ใน C++ สามารถแปลง double เป็น std::string ได้ง่ายด้วยฟังก์ชัน std::to_string (ตั้งแต่ C++11) ซึ่งอยู่ใน Header <string>

ตัวอย่างโค้ด

#include <iostream>
#include <string>
using namespace std;

int main() {
    double d = 238649.21316934;
    string s = to_string(d);
    cout << "Conversion of double to string: " << s;
    return 0;
}

ผลลัพธ์

Conversion of double to string: 238649.213169

รายละเอียดสำคัญ

  • to_string ใช้ Format เริ่มต้น: ทศนิยม 6 ตำแหน่ง (Fixed, 6 decimal places)
  • ค่าที่แปลงอาจมีความแม่นยำไม่ครบ (Floating point precision)
  • คืนค่า std::string โดยตรง ไม่ต้องจัดการ Buffer เอง

วิธีควบคุม Format (Precision, Scientific, etc.)

ใช้ std::ostringstream ร่วมกับ I/O Manipulators:


#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

string doubleToString(double value, int precision = 6, bool scientific = false) {
    ostringstream oss;
    if (scientific) {
        oss << scientific << setprecision(precision);
    } else {
        oss << fixed << setprecision(precision);
    }
    oss << value;
    return oss.str();
}

int main() {
    double d = 123.456789;
    cout << "Default: " << to_string(d) << "\n";
    cout << "Fixed 2: " << doubleToString(d, 2) << "\n";
    cout << "Fixed 10: " << doubleToString(d, 10) << "\n";
    cout << "Scientific 4: " << doubleToString(d, 4, true) << "\n";
    return 0;
}

ผลลัพธ์เพิ่มเติม

Default: 123.456789
Fixed 2: 123.46
Fixed 10: 123.4567890000
Scientific 4: 1.2346e+02

วิธีอื่นๆ (C++20)

  • std::format (C++20): std::format("{:.2f}", d) - ทรงพลังที่สุด
  • std::to_chars (C++17): Low-level, ไม่ allocate memory, เร็วที่สุด
  • sprintf/snprintf: C-style, ยังใช้ได้แต่ไม่แนะนำใน C++ Modern

ตารางเปรียบเทียบ

วิธีC++ Versionความยืดหยุ่นประสิทธิภาพแนะนำสำหรับ
to_stringC++11ต่ำ (Fixed 6 dec)ดีการใช้งานทั่วไป
ostringstreamC++98สูงปานกลางต้องการควบคุม Format
std::formatC++20สูงสุดดีโปรเจกต์ใหม่ ใช้ C++20
to_charsC++17ต่ำดีที่สุดHigh-performance, No allocation