Convert Double to String

Convert Double to String in C++

C++Beginner
C++
#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

Convert Double to String in C++

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.

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)

Methods for Conversion

Method 1: Using to_string()

cpp
string str1 = to_string(num);
  • Simple method, but has limitations
  • Default precision is typically 6 decimal places
  • No control over formatting
  • May show unnecessary trailing zeros

Method 2: Using stringstream with Precision

cpp
stringstream ss;
ss << fixed << setprecision(2) << num;
string str2 = ss.str();
  • Recommended method for formatted conversion
  • Full control over decimal precision
  • Can format with fixed or scientific notation
  • Professional output formatting

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

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.
  • Always use formatted precision for professional output, especially in financial applications.

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