Jump to content
  • Advertisement
Sign in to follow this  
hkBattousai

Extracting integer and fractional parts of a real number

This topic is 2899 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!