Page 1 of 1
Math problem: gte middle digit of number
Posted: Wed Jun 17, 2009 5:31 am
by ketbarat
Hi!
My very first post

I wonder what possibilities there are to get the middle digit of a number. Eg: 439 -> 3
I could do it with string functions but I'd like to handle the number as an integer and not as a string. Is there maybe a mathematical approach to do this? I heard something and I became curious.
Well thanx in advance
Re: Math problem: gte middle digit of number
Posted: Wed Jun 17, 2009 6:10 am
by onion2k
Just do it with the string functions and then cast it back to being an int with intval().
Re: Math problem: gte middle digit of number
Posted: Wed Jun 17, 2009 6:17 am
by ketbarat
That's the point.. I don't want to use string functions...
Re: Math problem: gte middle digit of number
Posted: Wed Jun 17, 2009 7:01 am
by onion2k
ketbarat wrote:That's the point.. I don't want to use string functions...
But you're treating it like a string already... there's no such thing as a "middle digit" in an int. The "middle" only exists when it's a string.
Re: Math problem: gte middle digit of number
Posted: Wed Jun 17, 2009 10:19 am
by allspiritseve
ketbarat wrote:That's the point.. I don't want to use string functions...
You can do it with math:
Code: Select all
function getDigit($num, $digit) {
return intval($num/pow(10,$digit-1))%10;
}
echo getDigit('3456', 3);
Re: Math problem: gte middle digit of number
Posted: Wed Jun 17, 2009 11:32 am
by onion2k
allspiritseve wrote:ketbarat wrote:That's the point.. I don't want to use string functions...
You can do it with math:
Code: Select all
function getDigit($num, $digit) {
return intval($num/pow(10,$digit-1))%10;
}
echo getDigit('3456', 3);
That's getting the
nth digit (specified by the second argument). You'd need to work out the length of the number to get the middle digit. Obviously you'd
normally use strlen() for that...
Re: Math problem: gte middle digit of number
Posted: Wed Jun 17, 2009 11:38 am
by allspiritseve
onion2k wrote:That's getting the nth digit (specified by the second argument). You'd need to work out the length of the number to get the middle digit. Obviously you'd normally use strlen() for that...
Ah, you're right. I misunderstood what the OP was looking for.
Re: Math problem: gte middle digit of number
Posted: Wed Jun 17, 2009 12:24 pm
by ketbarat
SWEET!
I knew you guys could help me out

That's the solution I was looking for

AWESOME
Thanx again.. (smile)