note 45727 deleted from ref.math by cmb
| From: | cmb@php.net | Date: | Sun, 21 Jul 2019 08:59:07 +0000 |
| Subject: | note 45727 deleted from ref.math by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211659@lists.php.net to get a copy of this message | ||
Note Submitter: donnieb819 at hotmail dot NOSPAM dot com
----
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