Convert Double to String

Convert Double to String in C++ (6 Programs)

BeginnerTopic: String Conversion Programs
Back

C++ Convert Double to String Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

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

int main() {
    double num = 123.456;
    
    // Method 1: Using to_string()
    string str1 = to_string(num);
    
    // Method 2: Using stringstream with precision
    stringstream ss;
    ss << fixed << setprecision(2) << num;
    string str2 = ss.str();
    
    cout << "Double: " << num << endl;
    cout << "String (method 1): " << str1 << endl;
    cout << "String (method 2): " << str2 << endl;
    
    return 0;
}
Output
Double: 123.456
String (method 1): 123.456000
String (method 2): 123.46

Understanding Convert Double to String

This program demonstrates 6 different methods to convert a double to a string: using to_string(), stringstream with precision, sprintf(), ostringstream, manual conversion, and using boost library.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents