Convert Double to String in C++

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

BeginnerString Conversion ProgramsExample 6 of 11
convert-double-to-string.cpp
1#include <iostream>
2#include <string>
3#include <sstream>
4#include <iomanip>
5using namespace std;
6
7int main() {
8 double num = 123.456;
9
10 // Method 1: Using to_string()
11 string str1 = to_string(num);
12
13 // Method 2: Using stringstream with precision
14 stringstream ss;
15 ss << fixed << setprecision(2) << num;
16 string str2 = ss.str();
17
18 cout << "Double: " << num << endl;
19 cout << "String (method 1): " << str1 << endl;
20 cout << "String (method 2): " << str2 << endl;
21
22 return 0;
23}

Output

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

What's going on

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)

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.

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.

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)

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"

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
1#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
1#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
1// Complex manual conversion handling integer and decimal parts
2// Extracts digits and formats with decimal point
3// 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
1#include <boost/lexical_cast.hpp>

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"

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).

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

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

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

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"

return 0;

This ends the program successfully.