# How take float fraction part?

Hi.

We have a little discussion here about next two code snippets.

Please, help us and take part in this pool.

Thanks.

Hi guys,

The question there is not “how to take float fraction part”, it’s

what of these two code snippets are more elegant, effective and shorter

Not always shorter code means better code. And not length was the root of our discussion. Everyone can see that second variant is shorter, but this is not a question.

Have no idea.

I would choose the second one simply because it looks cooler.

But: a very important question:

If fmod is more expensive than performing a subtraction and a floor, then I’d probably choose the first.

Maybe not ??

Any difference in the results? Like precision?

I think first result should be faster. Anyway, speed is not the goal in our case.

``````

\$ php -r '\$pi = 3.14159; echo \$pi - floor(\$pi), "\n";'

0.14159

\$ php -r '\$pi = 3.14159; echo fmod(\$pi, 1), "\n";'

0.14159

\$

``````

When adding a poll would be a good idea to offer more options… in this case "other (explain with a post)"…

Problem is if you have a negative number… then you should use

``````
\$fract = abs(\$float) - floor(abs(\$float));

``````

And there is a problem that the floating point arithmetic is not 100% accurate, so if that is a problem you need to use BCMath like:

``````

\$float = 312.81304618290502673;

\$fract = bcsub(abs(\$float),floor(abs(\$float)),20);

``````

And there is always the option to use string functions like:

``````
\$float = 734.342947582635127;

\$fract = strstr ( \$float, '.' );

``````

Edit:

Forgot one more way

``````
\$fract=\$float-(int)\$float;

``````

Maybe my question is dumb - but why didn’t you simply benchmark which of your two suggestions is faster?

Done.

mdomba, yes, you are right about negative numbers, we lost this case…

Now this one my favourite.

I don’t sure that we can see a difference on such little piece of code. My idea is translate it into bytecode,

in this case the difference can be seen by the human eye.

Of course you need to create a smart loop to measure the effect on a larger scale. Maybe check out this for some ideas:

http://www.phpbench.com/

I mean that even with loop it will not give us real picture, I think.

That’s why i added the word “smart” in my statement above …