Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a number by decimal point in php

Tags:

php

split

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.

like image 519
Par Avatar asked Jan 05 '09 11:01

Par


1 Answers

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.

like image 178
xtofl Avatar answered Oct 26 '22 22:10

xtofl