0

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.

Jvinniec
  • 616
  • 12
  • 18
  • 1
    You can use `std::stringstream` and you will get exactly the same result as you see when you use `std::cout` – Slava Sep 22 '16 at 20:09
  • You can use [std::setprecision](http://en.cppreference.com/w/cpp/io/manip/setprecision) – Galik Sep 22 '16 at 20:10
  • @Slava - Thanks, thats exactly what I needed. I guess this question can be closed now. – Jvinniec Sep 22 '16 at 20:19

0 Answers0