Member Avatar for diafol

Hi all, just walked into a door with a problem I recently helped out with.
I was testing whether a value was a positive power of 10 (1,10,100 ...) -> (0,1,2 ...).

So I thought I'd use log10(). Now I know that log10() returns a float type.
But testing this:

$x = 2;
$y = log10(100);
echo (is_int($x)) ? "$x is an integer" : "$x is not an integer"; 
echo (is_int($y)) ? "$y is an integer" : "$y is not an integer";

You guessed it, $x (2) is an integer, $y (2) is not an integer. Hmm.
Any ideas about how to get around this? I purposely do not want to force $y to be an integer as that would defeat the purpose of the test.
There must be a way, but for the life of me, it's eluding me at the moment. BTW - this is no biggie - just curious.

Recommended Answers

All 3 Replies

Member Avatar for diafol

OK, I got this:

$y = log10(100); 
echo (strpos($y,".")) ? "$y is not an integer" : "$y is an integer";

Seems to work, but it's really ugly. Any suggestions.

You can always do a check like this:

if (floor($y) == $y) { 
    // floor() should return a float too
    // if they are equal, you have a round log result
    // and you can safely cast it to an int
}
Member Avatar for diafol

Nice one Pritaeas - that's a lot smoother than strpos. I feel much happier about that. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.