-2

I have 2 string lat long values that I want to convert to double. When I run stod function some sig figs have been cut off from the original string.

double latitude = stod(latstr);
double longitude = stod(longstr);

cout<<"String values:"<<latstr<<","<<longstr<<endl;
cout<<"Double values:"<<latitude<<","<<longitude<<endl;

output:

String values:21.13134532, -155.325334532
Double values:21.131, -155.325
Lightsout
  • 3,454
  • 2
  • 36
  • 65
  • 1
    You sure that's because of `stod()`, and not how they are printed to the screen? – Steve Nov 02 '18 at 01:24
  • [std::setprecision](https://en.cppreference.com/w/cpp/io/manip/setprecision) – Steve Nov 02 '18 at 01:26
  • 1
    Also, if you use a debugger, it allows you to inspect the variables without the pesky `cout` getting in the way, only the debugger is in the way. See [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Steve Nov 02 '18 at 01:29
  • https://ideone.com/XEATC9 – Retired Ninja Nov 02 '18 at 01:31
  • @RetiredNinja `std::setprecision(std::numeric_limits::digits10)` interesting, thanks :) – Steve Nov 02 '18 at 01:32
  • 1
    Possible duplicate of [String to Double conversion C++](https://stackoverflow.com/questions/23449986/string-to-double-conversion-c) – shaocong Nov 02 '18 at 01:38
  • @shaocong that question solves my problem but the title is very misleading – Lightsout Nov 02 '18 at 01:52

1 Answers1

1

The problem isn't stod(), the problem is how the double is being printed to the screen with cout. This can be changed with std::setprecision.

// ...
#include <iomanip>
// ...
double latitude = stod(latstr);
double longitude = stod(longstr);

cout << "String values:" << latstr << "," << longstr << endl;
cout << "Double values:" << std::setprecision(10) << latitude << "," << longitude << endl;
Steve
  • 6,334
  • 4
  • 39
  • 67