Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Convert Double to String in C++

Convert a double to a string in C++ with to_string and with a stringstream using fixed and setprecision. Explains why to_string(123.456) gives 123.456000.

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}

Sample Output

String (method 1): 123.456000

to_string pads to six decimals.

String (method 2): 123.46

Rounded to two decimals.

In this one

  • That to_string always uses six digits after the decimal point
  • How a stringstream with fixed and setprecision controls digits
  • How rounding happens at the last kept digit
  • When each method fits

How it works

  1. 1

    num holds 123.456.

  2. 2

    to_string gives "123.456000".

  3. 3

    A stringstream set to fixed with precision 2 writes "123.46".

  4. 4

    ss.str() returns that text.

  5. 5

    Print all three.

Edge cases

Tiny value

Convert 0.0000001 with to_string.

to_string gives "0.000000", because it keeps only six decimal places. Use a stringstream with more precision or scientific format.

Rounding halfway

Convert 2.675 to two places.

You may get 2.67, not 2.68, because 2.675 is stored as slightly less than 2.675 in binary.

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)

#include <cstdio>

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

Method 4: Using ostringstream

#include <sstream>

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

Method 5: Manual Conversion

string str5 = "";

// Complex manual conversion handling integer and decimal parts

// Extracts digits and formats with decimal point

// Most control but most code

Manually extracts each digit
Most control but most code
Useful for learning how conversion works internally
Handles formatting, decimal points, and precision

Method 6: Using Boost Library

#include <boost/lexical_cast.hpp>

string str6 = boost::lexical_cast<string>(num);

Requires Boost library (external dependency)
Simple syntax but adds external dependency
Not standard C++, requires installation

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:

cout << "Double: " << num << endl;

cout << "String (method 1): " << str1 << endl;

cout << "String (method 2): " << str2 << endl;

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

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.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does to_string(1.5) return?

Pick an answer to check it.

Question 2

With fixed and setprecision(1), how is 9.96 written?

Pick an answer to check it.

Questions people ask

How do I drop trailing zeros?

Use a stringstream without fixed, or trim the zeros from the string afterwards.

Does setprecision change the number?

No. It only changes how the number is written as text.

Is there a C++20 option?

std::format("{:.2f}", num) in <format> does the same with less code, where your compiler supports it.