Conversion of string to double without scientific notation in C++

Viewed 483

I have a string variable and want to convert it into double without any scientific notation. I tried using std::stod but that doesn't work.

std::stringstream timestamp;
timestamp << t_val;
string test = timestamp.str();
cout << test << endl; // this gives 1506836639.96
double d = std::stod(test);
cout << d << endl; // This gives 1.50684e+09 instead of 1506836639.96

I tried using setprecision and fixed but I couldn't store the result into a variable. Is there a way I can store the value of test (1506836639.96) as a double?

1 Answers

The scientific notation has to do with std::cout, not the way the value is stored, so you must use std::fixed before you print the value:

std::cout << std::fixed << std::setprecision(2) << d << std::endl;

As you can see in the demo, this works fine, it should work for you as well.

As @goodvibration commented std::to_string also works but it's not possible to redefine, in a simple manner, the default number or decimal places in this case.

std::cout << std::to_string(d) << std::endl;

Live demo

Related