0

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
phuclv
  • 37,963
  • 15
  • 156
  • 475
Will Luce
  • 1,781
  • 3
  • 20
  • 33
  • What are you going to do with them once converted? Are you using GCC? It looks like it has some kind of Decimal support built in without needing a library - http://stackoverflow.com/questions/14096026/c-decimal-data-types#comment19516201_14096071 – TessellatingHeckler Nov 18 '14 at 23:35
  • The value can be stored exactly in binary or not doesn't depend on the length in decimal but whether it can be represented by a dyadic fraction or not. For example 0.1 can't be represented correctly in binary although it's very short, but 0.000244140625 can – phuclv Dec 19 '14 at 18:00
  • and **do not** use `atof` as well as `atoi`. It's unsafe. Use [`strtod`](http://en.cppreference.com/w/cpp/string/byte/strtof) instead because it provides error checking – phuclv Dec 19 '14 at 18:09
  • To print out the value with more precision use [this way](http://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) – phuclv Dec 19 '14 at 18:11

1 Answers1

-1

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
Will Luce
  • 1,781
  • 3
  • 20
  • 33
  • If you'd like responses to the question you're asking here, could you please create a new question? – Michael Gazonda Dec 19 '14 at 18:10
  • How does this answer your question? The [default precision is 6 digits](http://en.cppreference.com/w/cpp/io/ios_base/precision) and both 277.294 and 138.647 have 6 significand digits – phuclv Dec 19 '14 at 18:39
  • You're right, but I was needing to do arithmetic with numbers of a greater precision. My answer above proves that, although it will only cout 6 digits by default, it is storing (and therefore doing the arithmetic) with the entire number that I passed in. – Will Luce Dec 20 '14 at 00:18