Sign in to follow this  
hkBattousai

Extracting integer and fractional parts of a real number

Recommended Posts

I wrote a method for finding integer and fractional parts of a number. Unfortunately, it doesn't look like to be working for negative numbers. Can you please tell me what I'm doing wrong?

Method:
void Math::GetIntegerAndFractionalParts(long double num,
uint64_t & integer,
long double & fraction)
{
integer = static_cast<uint64_t>(num);
fraction = num - static_cast<long double>(integer);
}


Usage example:
long double num = 1.23;
long double frac;
uint64_t intg;
Math::GetIntegerAndFractionalParts(num, intg, frac);
std::cout << "Number : " << num << std::endl;
std::cout << "Integer part : " << intg << std::endl;
std::cout << "Fractional : " << frac << std::endl << std::endl;
num = -1.23;
Math::GetIntegerAndFractionalParts(num, intg, frac);
std::cout << "Number : " << num << std::endl;
std::cout << "Integer part : " << intg << std::endl;
std::cout << "Fractional : " << frac << std::endl << std::endl;
num = -567.89;
Math::GetIntegerAndFractionalParts(num, intg, frac);
std::cout << "Number : " << num << std::endl;
std::cout << "Integer part : " << intg << std::endl;
std::cout << "Fractional : " << frac << std::endl << std::endl;
num = Math::E; // Natural logarithm base
Math::GetIntegerAndFractionalParts(num, intg, frac);
std::cout << "Number : " << num << std::endl;
std::cout << "Integer part : " << intg << std::endl;
std::cout << "Fractional : " << frac << std::endl << std::endl;


Output:
Number       : 1.23
Integer part : 1
Fractional : 0.23

Number : -1.23
Integer part : 18446744073709551615
Fractional : -1.84467e+019

Number : -567.89
Integer part : 18446744073709551049
Fractional : -1.84467e+019

Number : 2.71828
Integer part : 2
Fractional : 0.718282

Share this post


Link to post
Share on other sites
Quote:
Original post by kuroioranda
You're casting to uint64_t. The "u" stands for "unsigned", meaning that it can't do negative numbers. Try casting to int64_t instead.

Ouu, I feel stupid at times like this...
Thank you very much.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this