C++ convert string to double with precision

1.8k views Asked by At

I need to convert string to double with precision up to 15 digits

I have read many articles and similar questions, and they suggested to use setprecision(15) when printing out the numbers to the screen.

For example:

string line = "34.9438553";
double lon1 = strtod(line.c_str(),NULL);

if I write

cout << lon1;

it will only print 34.9439 instead of 34.9438553

I could've written

cout << setprecision(15) << lon1;

and it will work, but I need the variable lon1 itself to have 15 digits precision because I need the entire numbers inside the variable and not only when I'm printing it out to the screen.

Does anyone know how to do it ?

1

There are 1 answers

0
Elliot Robinson On BEST ANSWER

setprecision sets the precision printed, not the precision of the double. strtod reads in the double to the minimum of the precisions available in either the double or the string (bounded by the string, in this case).

In short, you already have the full precision of your string in lon1 by using strtod.