Page 1 of 1

Math problem No.2: determine the number of digits in number

Posted: Thu Jun 18, 2009 3:47 am
by ketbarat
Hey there folks :)

My last question was answered really quickly so I am kinda hoping that this one will be as well :)
So I would like to replace the strlen() function with a custom function that only works for numbers. Is there maybe a way to determine the number of digits in a number w/o strlen()?

thanx in advance

Re: Math problem No.2: determine the number of digits in number

Posted: Thu Jun 18, 2009 6:59 am
by Jenk

Code: Select all

function digitLength($number) {
  $number =  abs($number);
  for ($i = 0; $number > 0; $i++) {
    $number = $number / 10;
  }
  return $i;
}

Re: Math problem No.2: determine the number of digits in number

Posted: Thu Jun 18, 2009 7:43 am
by Apollo
You can pull off something like this:

Code: Select all

$x = '714';
print(1+floor(log10($x))); // prints 3
But using a logarithm approach is kinda hairy, you're probably better off with something simple like:

Code: Select all

print(strlen(preg_replace('/\D/','',$x))); // the preg_replace removes all non-digits
Or if you want to ignore anything after the first non-digit (so e.g. "98a7" results in 2 digits, not 3), use:

Code: Select all

print(strlen(preg_replace('/\D.*$/','',$x))); // the preg_replace removes any non-digit and anything beyond
Still, you may wanna consider exactly what do you expect with strings like "0", "000", "00053", "-1", "05.000", "-0001", "0.5", ".5", ".50", "-000.5300", etc :)

Re: Math problem No.2: determine the number of digits in number

Posted: Thu Jun 18, 2009 11:16 am
by kaisellgren

Code: Select all

function digitLength($number,$base = 10)
{
 for ($i = 0, $number = abs(base_convert($number,$base,10)); (int) $number > 0; $i++)
  $number = $number / 10;
 return $i;
}
 
echo digitLength('FF',16);
You can specify the number base to use, which defaults to base 10. It also fixes an error that Jenk's code had. Enjoy.

Re: Math problem No.2: determine the number of digits in number

Posted: Thu Jun 18, 2009 3:56 pm
by Christopher
Not about theory or design, just a PHP question, so moved to PHP Code.