Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String to Double -- Loses Precision

Tags:

c++

string

double

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?

like image 876
Adam Avatar asked Oct 18 '13 20:10

Adam


1 Answers

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
$
like image 94
Waxrat Avatar answered Sep 28 '22 15:09

Waxrat