mhm
mhm

Reputation: 313

What's wrong with this string_to_number function?

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;
}

Upvotes: 1

Views: 165

Answers (3)

AdR
AdR

Reputation: 115

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

Upvotes: 1

Marco A.
Marco A.

Reputation: 43662

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

Upvotes: 2

Michael
Michael

Reputation: 968

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

Upvotes: 3

Related Questions