开发者

How to split float in PHP?

开发者 https://www.devze.com 2023-03-15 23:17 出处:网络
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 ve

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 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 :

  1. Preceding/trailing zeros. 12.0540 ( is 540/10000 or 54/1000 for you )

  2. 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..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号