How take float fraction part?
Posted 13 December 2010 - 05:44 PM
We have a little discussion here about next two code snippets.
Please, help us and take part in this pool.
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
Posted 13 December 2010 - 06:37 PM
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?
Posted 14 December 2010 - 01:52 AM
Posted 14 December 2010 - 02:57 AM
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, '.' );
Forgot one more way
Posted 14 December 2010 - 03:56 AM
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.