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 teaches you how to convert a double (floating-point number) into a string in C++. This conversion is essential when you need to display decimal numbers as text, format output with specific precision, write numbers to files, or combine numbers with strings. Understanding different conversion methods, especially for controlling decimal precision, is crucial for professional output formatting.

---

1. What This Program Does

The program converts a double (like 123.456) into a string (like "123.456" or "123.46" with formatting). This conversion is necessary because:

You need to combine decimal numbers with text in output
File operations often require string format
String manipulation functions work with strings, not doubles
Display formatting requires precise control over decimal places

Example:

Input double: 123.456
Output string (basic): "123.456000" (default precision)
Output string (formatted): "123.46" (2 decimal places)

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <string>
Essential for using the string data type.
Required for to_string() function and string operations.
3.#include <sstream>
Provides stringstream and ostringstream classes.
Allows formatting numbers before converting to string.
4.#include <iomanip>
Provides formatting manipulators like fixed, setprecision.
Essential for controlling decimal precision in output.

---

3. Declaring Variables

The program declares:

double num = 123.456;

double is the data type for storing decimal numbers with high precision.
num stores the double value 123.456 that we want to convert to a string.

---

4. Method 1: Using to_string() (Double to String)

string str1 = to_string(num);

This is a simple method, but has limitations:

to_string() is a built-in function (C++11 and later)
It converts the double to string with default precision
Default precision is typically 6 decimal places
No control over formatting

How it works:

to_string(123.456) converts to "123.456000" (default 6 decimal places)
Simple and straightforward
But may show unnecessary trailing zeros

Advantages:

Simplest syntax
Type-safe
No additional setup

Limitations:

No control over decimal precision
Always shows 6 decimal places (may have trailing zeros)
Cannot format with specific precision

Example:

double d = 123.456;

string s = to_string(d); // s = "123.456000" (6 decimals)

---

5. Method 2: Using stringstream with Precision

stringstream ss;

ss << fixed << setprecision(2) << num;

string str2 = ss.str();

This is the recommended method for formatted conversion:

stringstream ss creates an empty stream object
fixed sets fixed-point notation (not scientific)
setprecision(2) sets exactly 2 decimal places
ss << num inserts the formatted double into the stream
ss.str() extracts the formatted string

How it works:

1.Create an empty stringstream object
2.Set formatting options (fixed, setprecision)
3.Insert the double using the << operator
4.Extract the formatted string using .str() method

Advantages:

Full control over decimal precision
Can format with fixed or scientific notation
Can combine multiple values into one string
Professional output formatting

Example:

stringstream ss;

ss << fixed << setprecision(2) << 123.456;

string s = ss.str(); // s = "123.46"

Example with scientific notation:

stringstream ss;

ss << scientific << setprecision(3) << 123.456;

string s = ss.str(); // s = "1.235e+02"

---

6. Other Methods (Mentioned but not shown in code)

Method 3: Using sprintf() (C-style)

char buffer[50];

sprintf(buffer, "%.2f", num);

string str3 = buffer;

sprintf() formats and stores output in a character array
"%.2f" is the format specifier: %f for float/double, .2 for 2 decimal places
Requires a buffer (character array) to store the result
Less safe - buffer overflow risk if number is too large
#include <cstdio>

Method 4: Using ostringstream

ostringstream oss;

oss << fixed << setprecision(2) << num;

string str4 = oss.str();

ostringstream is specifically for output (output string stream)
Similar to stringstream but optimized for output only
Same functionality as stringstream for this use case
#include <sstream>

Method 5: Manual Conversion

string str5 = "";

Manually extracts each digit
Most control but most code
Useful for learning how conversion works internally
Handles formatting, decimal points, and precision
// Complex manual conversion handling integer and decimal parts
// Extracts digits and formats with decimal point
// Most control but most code

Method 6: Using Boost Library

string str6 = boost: :lexical_cast<string>(num);
Requires Boost library (external dependency)
Simple syntax but adds external dependency
Not standard C++, requires installation

---

#include <boost/lexical_cast.hpp>

7. Understanding Formatting Options

fixed

: Displays numbers in fixed-point notation (not scientific)

Example: 123.456 instead of 1.23456e+02

setprecision(n)

: Sets the number of decimal places

setprecision(2) shows 2 decimal places
Works with both fixed and scientific notation

scientific

: Displays numbers in scientific notation

Example: 1.23456e+02 instead of 123.456

Combining options

:

stringstream ss;

ss << fixed << setprecision(2) << 123.456; // "123.46"

ss << scientific << setprecision(3) << 123.456; // "1.235e+02"

---

8. Displaying Results

The program prints:

Output:

Double: 123.456
String (method 1): 123.456000
String (method 2): 123.46

Method 1 shows default precision (6 decimals), Method 2 shows formatted precision (2 decimals).

---

cout << "Double: " << num << endl;
cout << "String (method 1): " << str1 << endl;
cout << "String (method 2): " << str2 << endl;

9. When to Use Each Method

-

to_string()

: Simple cases where default precision is acceptable

-

stringstream with formatting

: Best for most cases - full control over precision and format

-

sprintf()

: Only for legacy code or when you need C compatibility

-

ostringstream

: Same as stringstream, slightly more explicit for output-only

-

Manual

: For learning or when you need custom conversion logic

-

Boost

: Avoid unless already using Boost library in your project

---

10. Precision Considerations

Default precision (to_string())

:

Shows 6 decimal places
May have trailing zeros: 123.0 becomes "123.000000"

Formatted precision (stringstream)

:

Exact control: setprecision(2) shows exactly 2 decimals
No trailing zeros beyond specified precision
Professional appearance: 123.0 becomes "123.00" (if precision=2)

For financial applications

: Always use formatted precision (typically 2 decimal places)

For scientific applications

: May need more precision or scientific notation

---

11. Common Formatting Patterns

Currency formatting

(2 decimal places):

stringstream ss;

ss << fixed << setprecision(2) << 123.456;

string currency = "$" + ss.str(); // "$123.46"

Percentage formatting

:

stringstream ss;

ss << fixed << setprecision(1) << 45.678;

string percent = ss.str() + "%"; // "45.7%"

Scientific notation

:

stringstream ss;

ss << scientific << setprecision(3) << 123456.789;

string sci = ss.str(); // "1.235e+05"

---

12. return 0;

This ends the program successfully.

---

Summary

Converting doubles to strings is essential for output formatting and string operations.
to_string() is simple but has limited formatting control (default 6 decimals).
stringstream with fixed and setprecision is the recommended method for formatted output.
sprintf() is a C-style method with buffer management concerns.
Always use formatted precision for professional output, especially in financial applications.
Choose the method based on your needs: simplicity vs. formatting control.

This program is fundamental for beginners learning how to format decimal numbers, control output precision, and create professional-looking displays in C++ programs.

Let us now understand every line and the components of the above program.

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.

Practical Learning Notes for Convert Double to String

This C++ program is part of the "String Conversion Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents