note 27498 modified in ref.math by aidan
| From: | aidan@php.net | Date: | Sat, 26 Jun 2004 03:04:18 +0000 |
| Subject: | note 27498 modified in ref.math by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-71706@lists.php.net to get a copy of this message | ||
This code will convert a decimal to it's fraction equivalent. The precision can be set by
changing PRECISION.
<?php
define(PRECISION, .01);
$count=0;
$result=array();
decimalToFraction($_REQUEST['dec'],$count,&$result);
$count = count($result);
$simp_fract = simplifyFraction($result,$count,1,$result[$count]);
echo $simpl_fract;
// Start of functions
/*
Converts a decimal to unsimplified fraction represented in an array
*/
function decimalToFraction($decimal,$count,$result) {
$a = (1/$decimal);
$b = ( $a - floor($a) );
$count++;
if ($b > .01 && $count <= 5) decimalToFraction($b,$count,&$result);
$result[$count] = floor($a);
}
/*
Simplifies a fraction in an array form that is returned from
decimalToFraction
*/
function simplifyFraction($fraction,$count,$top,$bottom) {
$next = $fraction[$count-1];
$a = ($bottom * $next) + $top;
$top = $bottom;
$bottom = $a;
$count--;
if ($count > 0) simplifyFraction($fraction,$count,$top,$bottom);
else {
return "<font size=1>$bottom/$top</font>";
}
}
?>
--was--
This code will convert a decimal to it's fraction equivalent. The precision can be set by
changing PRECISION.
-----------------------------------------------------------------
define(PRECISION, .01);
$count=0;
$result=array();
decimalToFraction($_REQUEST['dec'],$count,&$result);
$count = count($result);
$simp_fract = simplifyFraction($result,$count,1,$result[$count]);
echo $simpl_fract;
// Start of functions
/*
Converts a decimal to unsimplified fraction represented in an array
*/
function decimalToFraction($decimal,$count,$result) {
$a = (1/$decimal);
$b = ( $a - floor($a) );
$count++;
if ($b > .01 && $count <= 5) decimalToFraction($b,$count,&$result);
$result[$count] = floor($a);
}
/*
Simplifies a fraction in an array form that is returned from
decimalToFraction
*/
function simplifyFraction($fraction,$count,$top,$bottom) {
$next = $fraction[$count-1];
$a = ($bottom * $next) + $top;
$top = $bottom;
$bottom = $a;
$count--;
if ($count > 0) simplifyFraction($fraction,$count,$top,$bottom);
else {
return "<font size=1>$bottom/$top</font>";
}
}
http://php.net/manual/en/ref.math.php