Search code examples
c++doublefractions

Retrieving Fraction part from a double in C++


I am taking input in double and then typecast it in order to take out the fraction part. However when the input is a small number lets say 4294967295.2 , the fraction part is retrieved, but when I input a larger number then this, the fraction part becomes zero. I know it is some number thing but I am a little new to this stuff so. What is the reason for getting fraction part as zero when input number is like 9007199254740991.2.? Here is the code:

unsigned long long first,second;
double a,b,remainderA,remainderB;
cout << "Enter first number:\n"<< endl;
cin>> a;
cout << "\nEnter second number:\n"<< endl;
cin >> b;

first=(unsigned long long) a;
second=(unsigned long long) b;

remainderA=a-first;
remainderB=b-second;


cout<<remainderA<<endl;

Regards


Solution

  • It's simply a matter of precision. A double has 52 Bits of mantissa which gives about 15-17 bits of decimal digits. Your second example hits this Limit and the fraction (0.2) most likly gets not stored within the double.