How would you find the fractional part of a floating point number in PHP?
For example, if I have the value 1.25
, I want to return 0.25
.
$x = $x - floor($x)
My PHP skills are lacking but you could minus the result of a floor from the original number
You can use fmod function:
$y = fmod($x, 1); //$x = 1.25 $y = 0.25
However, if you are dealing with something like perlin noise or another graphical representation, the solution which was accepted is correct. It will give you the fractional part from the lower number.
i.e:
.25
: 0 is integer below, fractional part is .25-.25
: -1 is integer below, fractional part is .75With the other solutions, you will repeat 0 as integer below, and worse, you will get reversed fractional values for all negative numbers.
Don't forget that you can't trust floating point arithmetic to be 100% accurate. If you're concerned about this, you'll want to look into the BCMath Arbitrary Precision Mathematics functions.
$x = 22.732423423423432;
$x = bcsub(abs($x),floor(abs($x)),20);
You could also hack on the string yourself
$x = 22.732423423423432;
$x = strstr ( $x, '.' );
The answer provided by nlucaroni will only work for positive numbers. A possible solution that works for both positive as well as negative numbers is:
$x = $x - intval($x)