I am trying to convert a string to a double, however when i use stod() the double has lost some of it's decimal places. Here is the relevant code :
cout << line3 << endl;
float temp = stod(line3);
cout << temp << endl;
For example, when line3 is "4.225308642", temp outputs as 4.22531. What is causing the shortening of the number and how can I fix it?
CodePudding user response:
There are two aspects to consider here.
First, formating on a IOStream by default has a precision of 6 significant digits. That explains your result. You can increase the precision with the manipulator setprecision
.
Then, float
by itself has a limited precision of about 6 decimal digits as well. Although you can display more, they will be the result of displaying a binary float as decimal, not really an increase of the precision. You can get about 15 decimal digits of precision by using double.
So combining the two, the program
#include <iostream>
#include <string>
#include <iomanip>
int main() {
std::string line3 = "4.225308642";
std::cout << line3 << '\n';
float tempf = stof(line3);
double tempd = stod(line3);
std::cout << "default: float=" << tempf << ", double=" << tempd << '\n';
std::cout << std::setprecision(20);
std::cout << "precision(20): float=" << tempf << ", double=" << tempd << '\n';
}
has for result:
4.225308642
default: float=4.22531, double=4.22531
precision(20): float=4.2253084182739257812, double=4.2253086419999998924
Note again that the last digits result of displaying a binary format. There is a precision after which you can't expect a decimal representation matching the input, and 20 is greater than that. That aspect is explained in more details here.