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.
1#include <iostream>2#include <string>3#include <sstream>4using namespace std;56int main() {7 string str = "123.456";89 // Method 1: Using stod()10 double num1 = stod(str);1112 // Method 2: Using stringstream13 stringstream ss(str);14 double num2;15 ss >> num2;1617 cout << "String: " << str << endl;18 cout << "Double (method 1): " << num1 << endl;19 cout << "Double (method 2): " << num2 << endl;2021 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
str holds "123.456".
- 2
stod(str) returns 123.456.
- 3
A stringstream reads the same text into num2.
- 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:
Example:
Header Files Used
Declaring Variables
The program declares:
string str = "123.456";
Method 1: Using stod() (String to Double)
double num1 = stod(str);
This is the most modern and recommended method in C++:
How it works:
Advantages:
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:
How it works:
Advantages:
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());
Method 4: Using sscanf() (C-style)
#include <cstdio>
double num4;
sscanf(str.c_str(), "%lf", &num4);
Method 5: Using strtod() (C-style)
#include <cstdlib>
char* endPtr;
double num5 = strtod(str.c_str(), &endPtr);
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;
How Manual Conversion Works (Step-by-Step)
Understanding manual conversion helps you understand the concept:
For string "123.456":
The process:
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
Floating-point limitations:
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
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;