Re: counting the digits in a number, exponential format problem [message #171031 is a reply to message #171026] |
Wed, 15 December 2010 15:53 |
mhandersen
Messages: 5 Registered: December 2010
Karma:
|
Junior Member |
|
|
@Alvaro: thanks for your reply. i am by no means a PHP expert
(obviously) so this is all good information.
> Alright, you don't really want to know the length of a numeric variable.
> You know to want the length of its string representation. That's easy to
> calculate but clearly depends of how you want to display the number:
exactly!!! the only problem is that i have no control of how the
number comes to me, nor how it is displayed later. however, it is
always displayed using full decimal form with the least number of
digits and no commas. for example: 1234 not 1,234.0, etc. the problem
i was having is how PHP changes its conversion process to strings for
float from E-4 to E-5. that is what has been really throwing me off.
however, i think i have a working solution now for my original
problem. below is my function if anyone cares to see my solution:
function numberOfDigits($value)
{
if(!is_numeric($value))
{
return 0;
}
if((int)$value == $value)
{
return strlen((int)$value);
}
for($i=1; $i<=10; $i+=1)
{
$temp = $value * pow(10,$i);
if((int)$temp == $temp)
{
if((int)$value == 0)
{
return $i + 1;
}
else
{
return strlen($temp);
}
}
}
return strlen((int)$value) + 10;
}
echo numberOfDigits(1); // '1'
echo numberOfDigits(123.456); // '6'
echo numberOfDigits(1.0); // '1'
echo numberOfDigits(0.33); // '3'
echo numberOfDigits(0.033); // '4'
echo numberOfDigits(0.0033); // '5'
echo numberOfDigits(0.00033); // '6'
echo numberOfDigits(3.3E-5); // '7'
echo numberOfDigits(3.3E-6); // '8'
echo numberOfDigits(3.3E-7); // '9'
i use a for loop which only goes to $i=10 because i really only care
about numbers down to E-9ish. clearly you could change that to a while
loop or something and make the function more general.
thanks again everyone for all the help and information.
|
|
|