Precision when converting a string decimal number

404 views Asked by At

I need a way to convert this string into its exact number representation. I've tried quite a few things and, from what I know, this should work (famous last words). I'm trying to stay away from installing libraries and I have A LOT of these numbers to convert.

I understand that it is difficult to represent long decimal numbers in binary, but I need a solution.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
   string data = "138.6470184568";
   cout << atof(data.c_str()) << endl;

   return 0;
}

Output

138.647
1

There are 1 answers

3
Will Luce On BEST ANSWER

Turns out that it is converting correctly, but, when asked to cout the number, it only gives 3-4 decimal places. Anyone know why?

#include <iostream>
#include <stdlib.h>
#include <iomanip>

using namespace std;

int main()
{
   string data1 = "138.6470184568";
   string data2 = "138.6470184568";
   double data3 = atof(data1.c_str()) + atof(data2.c_str());

   cout << data3 << endl;
   cout << setprecision(15) << data3;

   return 0;
}

Gives

277.294
277.2940369136