Let's say we have 12.054 and I want to split it to three variables like $whole_number=12 $numerator=54 and $denominator=1000. Could you help me?
A straight-forward approach - not very academic, but it works for PHP ;-):
$float = 12.054;
$parts = explode('.', (string)$float);
$whole_number = $parts[0];
$numerator = trim($parts[1], '0');
$denominator = pow(10, strlen(rtrim($parts[1], '0')));
Some more work might be needed to ensure that edge case work too (trailing 0s, no decimal part at all, etc.).
Here is something to get you started , based on simple type conversions.
http://codepad.org/7ExBhTMS
However, there are many cases to consider like :
Preceding/trailing zeros. 12.0540 ( is 540/10000 or 54/1000 for you )
Handling decimals with no fractional part eg. 12.00 .
$val = 12.054;
print_r(splitter($val));
function splitter($val)
{
$str = (string) $val ;
$splitted = explode(".",$str);
$whole = (integer)$splitted[0] ;
$num = (integer) $splitted[1];
$den = (integer) pow(10,strlen($splitted[1]));
return array('whole' => $whole, 'num' => $num,'den' => $den);
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With