I'm having an issue when trying to save a double to a string, then convert that string back to a double again. The problem is that the string appears to only store the first 6 decimal places, so when my double is too small, the stored value is "0.000000" and thus 0 when i convert it back to double.
I wrote a quick compilable to demonstrate the problem:
#include <string>
#include <iostream>
int main ()
{
// Create a very small double
double initial_val = 2.9e-9 ;
// Convert the double to a string
std::string string_val = std::to_string(initial_val) ;
// Convert the string back to a double
double final_val = std::stod(string_val) ;
// Print out the result
std::cout << "initial_val: " << initial_val << std::endl;
std::cout << "string_val : " << string_val << std::endl;
std::cout << "final_val : " << final_val << std::endl;
std::cout << "difference : " << initial_val - final_val << std::endl;
return 0;
}
This gives the output:
initial_val: 2.9e-09
string_val : 0.000000
final_val : 0
difference : 2.9e-09
Is there a better way to convert my double to a string so that it will still be useable when I convert it back to a double? Unfortunately, a string is what I have to work with for the class I'm using.
EDIT
Slava's comment below fixes the issue. Saving the string instead as
std::stringstream stream ;
stream << initial_val ;
std::string string_val = stream.str() ;
leads to there being no difference in initial_val and final_val.