1

I have a string_to_number function that converts string to double. Why is this not working in this case?

#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
using namespace std;

double string_to_number( string text )
{
    double value;
    istringstream ( text ) >> value;
    return value;
}

int main()
{
    string text = "1234567890987654321";
    double value = string_to_number( text );
    cout << fixed << setprecision( 0 ) << value << endl; // 123456789098765400 ??? What happened to "321" ?!!

    return 0;
}
mhm
  • 313
  • 1
  • 5
  • 12
  • 1
    Nothing is wrong with the function. [Read this](http://www.validlab.com/goldberg/paper.pdf). –  Feb 06 '14 at 11:24
  • 2
    Do you *have* to write your own? Can't you use e.g. [`std::stoll`](http://en.cppreference.com/w/cpp/string/basic_string/stol) (or [`std::stold`](http://en.cppreference.com/w/cpp/string/basic_string/stof)). – Some programmer dude Feb 06 '14 at 11:24
  • Have you try to do `std::cout << 1234567890987654321.` the same way ? – Jarod42 Feb 06 '14 at 11:40

3 Answers3

3

That number is too large to fit in a single double, so its being truncated.

Michael
  • 979
  • 6
  • 13
2

Take a look at the IEEE format for a double.

There's a limit when storing integers without losing precision into doubles as this answer greatly summarizes: https://stackoverflow.com/a/1848762/1938163

Loss of precision first occurs with 2^53+1 and your number is exactly greater than that

   9007199254740993
1234567890987654321
Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246
1

the number is just too large for the double representation, so it's being truncated. Mind that the size of 'long double' type is architecture dependent. Please look here MSDN: sizeof(double)=8 and sizeof(long double)=8, whilst the same check implemented on Debian 64bits shows sizeof(double)=8 and sizeof(long double)=16.

Perhaps more portable way would be using external libraries dealing with big numbers, like boost multiprecision or GNU GMP

AdR
  • 115
  • 7