What's the best way to get the fractional part of a float in PHP?

$x = $x - floor($x)

$x = fmod($x, 1);

Here's a demo:

<?php
$x = 25.3333;
$x = fmod($x, 1);
var_dump($x);

Should ouptut

double(0.3333)

Credit.


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, '.' );

Tags:

Php