Adam
Adam

Reputation: 510

Converting String to Double -- Loses Precision

I am having trouble converting a string to a double. I am given a string with lat/long coordinates in the format of 33.9425/N 118.4081/W

I first call my function trimLastChar(std::string& input) twice, which will remove the the North, South, East, West characters and then the forward slash. This function correctly returns 33.9425 and 118.4081 respectfully as a std::string.

I am using the following code to convert my std::string to a double...however the problem is, the conversion losses precision -- I suspect it gets rounded?.

// Location In String is what trimLastChar returns
std::stringstream stream(locationInString);
std::cout << "DEBUG: before: " << locationInString << " ";
// output is a double* output = new double passed by reference to my function
stream >> output;
std::cout << output << std::endl;

The output in this case would produce:

33.9425 
118.408

As you notice, the correct value should be 118.4081 but the 1 is missing...

Any ideas how to fix? Or more important, why is this happening?

Upvotes: 5

Views: 2238

Answers (2)

Waxrat
Waxrat

Reputation: 2185

The precision wasn't lost on input. It's being lost on output.

#include <iostream>
using std::cout;
using std::endl;
int main()
{
  double v = 118.4081;
  cout << v << endl;
  cout.precision(10);
  cout << v << endl;
}

outputs:

$ g++ -Wall x.cpp && ./a.out
118.408
118.4081
$

Upvotes: 7

Daniel Frey
Daniel Frey

Reputation: 56863

You probably have more digits than the output shows. By default, only a small number of digits is shown, you need to use std::setprecision to see more digits. Try

std::cout << std::setprecision(10) << output << std::endl;

Upvotes: 3

Related Questions