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

Convert String to Double in C++

Convert text like "123.456" to a double in C++ with stod or stringstream. Covers exceptions on bad text, locale-free parsing, and why a digit can look off.

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

Sample Output

Double (method 1): 123.456

From stod.

In this one

  • How stod parses decimal text
  • How stringstream >> reads a double
  • What happens with invalid or partly valid text
  • Why some decimals cannot be stored exactly

How it works

  1. 1

    str holds "123.456".

  2. 2

    stod(str) returns 123.456.

  3. 3

    A stringstream reads the same text into num2.

  4. 4

    cout prints both with its default six significant digits.

Edge cases

Scientific notation

Set str = "1.5e3".

Both methods understand exponent form and return 1500.

Comma as decimal point

Set str = "3,14".

stod stops at the comma and returns 3. It does not throw because 3 is a valid prefix.

What's going on

The program converts a string like "123.456" into a double value 123.456. This conversion is necessary because:

User input from cin is often read as strings
File data containing decimal numbers comes as strings
Network data and APIs return numbers as strings
You need double precision for accurate decimal calculations

Example:

Input string: "123.456"
Output double: 123.456

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 stod() function and string operations.
3.#include <sstream>
Provides stringstream class for string-based input/output operations.
Allows treating strings as streams for parsing.

Declaring Variables

The program declares:

string str = "123.456";

string is the data type for storing text.
str stores the string "123.456", which contains a decimal number as text.
Note: "123.456" is text, not a number, until converted.

Method 1: Using stod() (String to Double)

double num1 = stod(str);

This is the most modern and recommended method in C++:

stod() stands for "string to double"
It's part of the <string> header (C++11 and later)
It automatically handles the conversion
It throws exceptions for invalid input
Handles scientific notation (e.g., "1.23e2" = 123.0)

How it works:

stod("123.456") reads the string and converts it to double 123.456
Automatically handles decimal points
Can parse scientific notation: stod("1.23e2") = 123.0
If the string contains non-numeric characters, it converts up to the first invalid character

Advantages:

Simple and clean syntax
Built-in error handling (throws exceptions)
Handles leading/trailing whitespace automatically
Supports scientific notation
Most efficient for simple conversions

Example:

double d1 = stod("123.456"); // 123.456

double d2 = stod("1.23e2"); // 123.0 (scientific notation)

double d3 = stod(" 45.67 "); // 45.67 (whitespace handled)

Method 2: Using stringstream

stringstream ss(str);

double num2;

ss >> num2;

This method uses stringstream, which treats a string like an input stream:

stringstream ss(str) creates a stream from the string
ss >> num2 extracts the double from the stream, just like cin >> num

How it works:

1.Create a stringstream object from the string
2.Use the extraction operator (>>) to read the double
3.The stream automatically converts the string to double

Advantages:

Very flexible - can convert multiple values
Similar syntax to cin, making it familiar
Can handle multiple types in one stream
Good for parsing complex input

Example for multiple values:

stringstream ss("123.45 67.89 10.11");

double a, b, c;

ss >> a >> b >> c; // a=123.45, b=67.89, c=10.11

Other Methods (Mentioned but not shown in code)

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

#include <cstdlib>

double num3 = atof(str.c_str());

atof() is a C function that converts C-style strings to double
Requires converting C++ string to C-string using .c_str()
Returns 0.0 for invalid input (no error checking)
Less safe than stod()
Stands for "ASCII to float" (but returns double)

Method 4: Using sscanf() (C-style)

#include <cstdio>

double num4;

sscanf(str.c_str(), "%lf", &num4);

sscanf() reads formatted input from a string
"%lf" is the format specifier for double (long float)
Similar to scanf() but reads from a string
More control over format, but more complex

Method 5: Using strtod() (C-style)

#include <cstdlib>

char* endPtr;

double num5 = strtod(str.c_str(), &endPtr);

strtod() is a C function with better error handling than atof()
endPtr points to the first character that couldn't be converted
Can check if conversion was successful by examining endPtr
More control than atof() but still C-style

Method 6: Manual Conversion

double num6 = 0.0;

double sign = 1.0;

int i = 0;

// Handle negative sign

if (str[0] == '-') { sign = -1.0; i = 1; }

// Convert integer part

while (i < str.length() && str[i] != '.') {

num6 = num6 * 10 + (str[i] - '0');

i++;

}

// Convert decimal part

if (i < str.length() && str[i] == '.') {

i++;

double fraction = 0.1;

while (i < str.length()) {

num6 += (str[i] - '0') * fraction;

fraction /= 10;

i++;

}

}

num6 *= sign;

Manually processes each character
Most control but most code
Useful for learning how conversion works internally
Handles decimal point and negative numbers

How Manual Conversion Works (Step-by-Step)

Understanding manual conversion helps you understand the concept:

For string "123.456":

1.Integer part: Process "123"
Start: num = 0
'1': num = 0 * 10 + 1 = 1
'2': num = 1 * 10 + 2 = 12
'3': num = 12 * 10 + 3 = 123
2.Decimal part: Process ".456"
After decimal point, use fractional weights
'4': num += 4 * 0.1 = 123.4
'5': num += 5 * 0.01 = 123.45
'6': num += 6 * 0.001 = 123.456

The process:

Integer part: Multiply by 10 and add digit (left to right)
Decimal part: Add digit multiplied by decreasing powers of 10 (0.1, 0.01, 0.001, ...)

Displaying Results

The program prints:

cout << "String: " << str << endl;

cout << "Double (method 1): " << num1 << endl;

cout << "Double (method 2): " << num2 << endl;

Output:

String: 123.456

Double (method 1): 123.456

Double (method 2): 123.456

Both methods produce the same double value.

Precision and Accuracy

Double precision: double can represent approximately 15-17 significant digits

More precise than float (which has ~7 digits)
Suitable for most scientific and financial calculations

Floating-point limitations:

Some decimal numbers cannot be represented exactly in binary
Example: 0.1 + 0.2 might not equal exactly 0.3
This is a limitation of binary representation, not the conversion method

For exact decimal arithmetic: Consider using decimal libraries or fixed-point arithmetic for financial applications.

Error Handling

Different methods handle errors differently:

stod(): Throws std::invalid_argument or std::out_of_range exceptions

try {

double num = stod("abc");

} catch (const std::exception& e) {

// Handle error

}

atof(): Returns 0.0 for invalid input (no way to distinguish error from actual 0.0)

strtod(): Sets endPtr to indicate where conversion stopped

char* endPtr;

double num = strtod("123.45abc", &endPtr);

if (*endPtr != '0') {

// Partial conversion or error

}

stringstream: Sets failbit on error

if (ss.fail()) {

// Handle error

}

Best Practice: Use stod() with try-catch for robust error handling.

When to Use Each Method

stod(): Best for most cases - simple, safe, modern C++
stringstream: Best when converting multiple values or mixing types
atof(): Only for legacy code - no error checking
strtod(): When you need C compatibility with better error handling
sscanf(): When you need complex format parsing
Manual: For learning or when you need custom conversion logic

return 0;

This ends the program successfully.

Quiz

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

Question 1

What does stod("2.5kg") return?

Pick an answer to check it.

Question 2

What does cout print for 123.456 by default?

Pick an answer to check it.

Questions people ask

Why does 0.1 print as 0.1 but compare oddly?

0.1 has no exact binary form. cout rounds it to six digits for display, but the stored value is very slightly different.

What does stod throw?

invalid_argument when no number can be read, and out_of_range when the value is too large for double.

How do I print more digits?

cout << setprecision(10) << num1;