Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split float in PHP?

Tags:

php

math

numbers

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?

like image 745
Templar Avatar asked Aug 05 '26 08:08

Templar


2 Answers

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

like image 87
Stefan Gehrig Avatar answered Aug 06 '26 20:08

Stefan Gehrig


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);
    }
    
    
    
    ?>
    
like image 25
DhruvPathak Avatar answered Aug 06 '26 20:08

DhruvPathak