# Extracting Digits From a Number

I need some code to extract any digit from a 10 digit number the code I have come up with is -

int(value/pow(10,(9-digit))) % 10

where digit is the position of the digit to be calculated starting from the left one being 0 to 9 for the rightmost one. This is not working at all and generally seems to be returning 0 for most digits.
Any ideas?

Thanks

could this be what you're looking for? seems that whenever someone is looking for a specific digit in a value it's for the purpose of displaying

``````9
8
7
6
5
4
3
2
1
``````
``````void setup() {
Serial.begin(9600);

long n = 987654321;
char s;

sprintf (s, "%ld", n);

for (unsigned i = 0; i < strlen (s); i++)
Serial.println (s [i]);
}

void loop() {}
``````

This is not working at all

The pow() function uses floating point and mathematical approximations. It does not return the integer values that you are probably expecting.

jremington:
The pow() function uses floating point and mathematical approximations. It does not return the integer values that you are probably expecting.

So pow cast to integer will not accurately give me the powers of 10?

Not in general.

So, is there an integer version of pow, or a better way to get the powers of 10?

Should work with strings:

(haven't tried this)

``````#include "String.h"

void setup() {

long number = 465738;

String str = String(number); // Convert number to string

// now access the digits
char digit = str.charAt(3);

// digit should now be '5'
}
``````

It is easy to write an integer version of pow(), but there are much better ways to do what you want to do. Most people use integer division and remainder operators "/" and "%" to get the individual digits.

For example:

``````int n = 1234;
int units = n%10; //the 4
int tens  = (n/10)%10; //the 3
``````

Try this for fun:

``````void setup() {
Serial.begin(9600);
for(int i=0; i<6; i++)
Serial.println((int)pow(10,i));
}

void loop() {}
``````

OK, embarrassingly, having just tried the converting to a string code, I was getting the same problem and found that it was because I had my 10 digit number declared as int - changed this to long and all is working. Many thanks to all of you for getting me there.