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