tags:

views:

1301

answers:

4

How do I split a number by the decimal point in php?

I've got $num = 15/4; which turns $num into 3.75. I would like to split out the 3 and the 75 parts, so $int = 3 and $dec = 75. My non-working code is:

$num = 15/4; // or $num = 3.75;
list($int, $dec) = split('.', $num);

but that results in empty $int and $dec.

Thanks in advance.

+4  A: 
$num = 15/4; // or $num = 3.75;
list($int, $dec) = explode('.', $num);
Ólafur Waage
+5  A: 

Try explode

list($int,$dec)=explode('.', $num);

as you don't really need to use a regex based split. Split wasn't working for you as a '.' character would need escaping to provide a literal match.

Paul Dixon
Note that you _do_ lose precision this way - don't base calculations on that.
xtofl
+1  A: 
$int = $num > 0 ? floor($num) : ceil($num);
$dec = $num - $int;

If you want $dec to be positive when $num is negative (like the other answers) you could do:

$dec = abs($num - $int);

edit I fixed original after Paul Dixon informed me it would be broken by negative numbers.

Tom Haigh
Fails for negative numbers, e.g. if $num=-17.3, then $int=18 and $dec=0.7
Paul Dixon
ok, modified it.
Tom Haigh
+6  A: 

If you explode the decimal representation of the number, you lose precision. If you don't mind, so be it (that's ok for textual representation). Take the locale into account! We Belgians use a comma (at least the non-programming ones :).

If you do mind (for computations e.g.), you can use the floor function:

$num = 15/4
$intpart = floor( $num )    // results in 3
$fraction = $num - $intpart // results in 0.75

Note: this is for positive numbers. For negative numbers you can invert the sign, use the positive approach, and reinvert the sign of the int part.

xtofl