• Advertisement

Archived

This topic is now archived and is closed to further replies.

Finding the decimal digits of an integer

This topic is 5951 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 can''t seem to find an easy way to extract a single decimal digit from an int. I would like to have a function that would return an int of the single digit I ask for. For instance if I had: int x = 5436; int digitToGet = 1; cout << getDigit(x, digitToGet); I would like to have a 6 print on the screen. BTW if I have the digits in the wrong order, and the first digit is the 5 I apologize. Any help would be appreciated.

Share this post


Link to post
Share on other sites
Advertisement
Even better:

int x = 5436;
cout << x % 10 << endl; // print 6 to screen


You can use this property to obtain any number of digits from any number in any base:

// default to base 10
int GetDigits(int num, int digits, int base = 10)
{
int mod = 1;
while(digits)
{
mod *= base;
--digits;
}
return (num % mod);
}




I wanna work for Microsoft!

Share this post


Link to post
Share on other sites

  • Advertisement