#### Archived

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

# Finding the decimal digits of an integer

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

## 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 on other sites
use itoa

Magmai Kai Holmlor
- Not For Rent

##### Share on other sites
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 10int GetDigits(int num, int digits, int base = 10){  int mod = 1;  while(digits)  {    mod *= base;    --digits;  }  return (num % mod);}

I wanna work for Microsoft!

• 40
• 12
• 10
• 10
• 9
• ### Forum Statistics

• Total Topics
631367
• Total Posts
2999594
×