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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ketbarat
Forum Newbie
Posts: 4
Joined: Wed Jun 17, 2009 5:28 am

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

Post 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
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

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

Post by Jenk »

Code: Select all

function digitLength($number) {
  $number =  abs($number);
  for ($i = 0; $number > 0; $i++) {
    $number = $number / 10;
  }
  return $i;
}
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

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

Post 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 :)
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

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

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

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

Post by Christopher »

Not about theory or design, just a PHP question, so moved to PHP Code.
(#10850)
Post Reply