# 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.

## 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 baseMath::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.23Integer part : 1Fractional   : 0.23Number       : -1.23Integer part : 18446744073709551615Fractional   : -1.84467e+019Number       : -567.89Integer part : 18446744073709551049Fractional   : -1.84467e+019Number       : 2.71828Integer part : 2Fractional   : 0.718282

##### Share on other sites
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.

##### Share on other sites
Quote:
 Original post by kuroiorandaYou'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.

1. 1
Rutin
32
2. 2
3. 3
4. 4
5. 5

• 13
• 9
• 9
• 9
• 14
• ### Forum Statistics

• Total Topics
633317
• Total Posts
3011336
• ### Who's Online (See full list)

There are no registered users currently online

×