note 45727 added to ref.math

From: Date: Thu, 16 Sep 2004 12:58:00 +0000
Subject: note 45727 added to ref.math
Groups: php.notes 
Request: Send a blank email to php-notes+get-76824@lists.php.net to get a copy of this message
Method to convert an arbitrary decimal number to its most reduced fraction form (so a string is returned, this method would probably be used for output formatting purposes.) There were other methods similar to this one on the page, but none did quite what I wanted. It's maybe not the most elegant code, but it gets the job done. Hope this helps someone. An iterative form of Euclid's algorithm is used to find the GCD. <?php function dec2frac( $decimal ) { $decimal = (string)$decimal; $num = ''; $den = 1; $dec = false; // find least reduced fractional form of number for( $i = 0, $ix = strlen( $decimal ); $i < $ix; $i++ ) { // build the denominator as we 'shift' the decimal to the right if( $dec ) $den *= 10; // find the decimal place/ build the numberator if( $decimal{$i} == '.' ) $dec = true; else $num .= $decimal{$i}; } $num = (int)$num; // whole number, just return it if( $den == 1 ) return $num; $num2 = $num; $den2 = $den; $rem = 1; // Euclid's Algorithm (to find the gcd) while( $num2 % $den2 ) { $rem = $num2 % $den2; $num2 = $den2; $den2 = $rem; } if( $den2 != $den ) $rem = $den2; // now $rem holds the gcd of the numerator and denominator of our fraction return ($num / $rem ) . "/" . ($den / $rem); } ?> Examples: echo dec2frac( 10 ); echo dec2frac( .5 ); echo dec2frac( 5.25 ); echo dec2frac( .333333333 ); yields: 10 1/2 21/4 333333333/1000000000 ---- Manual Page -- http://www.php.net/manual/en/ref.math.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+45727 Delete -- http://master.php.net/manage/user-notes.php?action=delete+45727&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+45727&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#76824) next »