How to split float in PHP?
Let's say we have 12.054 and I want to split it to three variables like $whole_number=开发者_如何学Python12
$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 0
s, 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); } ?>
Try This
<?
$no = 12.54;
$arr = explode(".", $no);
$full_no = $arr[0].$arr[1];
for($i = 0; $i < strlen($arr[1]); $i++) $denominator = $denominator."0";
$denominator = "1".$denominator;
$numerator = $full_no % $denominator;
$whole_no = $full_no / $denominator;
echo "Denominator = ". $denominator ."<br>";
echo "Numerator = ". $numerator ."<br>";
echo "Whole No = ". (int)$whole_no ."<br>";
?>
Output :
Denominator = 100
Numerator = 54
Whole No = 12
Output for 12.054 :
Denominator = 1000
Numerator = 54
Whole No = 12
I hope this will help you..
精彩评论