ภาพรวม
ใน 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_string | C++11 | ต่ำ (Fixed 6 dec) | ดี | การใช้งานทั่วไป |
| ostringstream | C++98 | สูง | ปานกลาง | ต้องการควบคุม Format |
| std::format | C++20 | สูงสุด | ดี | โปรเจกต์ใหม่ ใช้ C++20 |
| to_chars | C++17 | ต่ำ | ดีที่สุด | High-performance, No allocation |