Zend - The PHP Company




Math

Add Code


Decimal to Fraction  

Type: code fragment
Added by: zak
Entered: 09/06/2000
Last modified: 08/12/1999
Rating: - (fewer than 3 votes)
Views: 8283
A function that converts numbers with decimal remainders to numbers with fractional remainders.


<?
function decimal_to_fraction ($number)
{
    list (
$whole$numerator) = explode ('.'$number);
    
    
$denominator str_repeat (0strlen ($numerator));
    
    
$GCD GCD ($numerator$denominator);
    
    
$numerator /= $GCD;
    
$denominator /= $GCD;
    
    return 
sprintf ('%d <sup>%d</sup>/<sub>%d</sub>',
        
$whole$numerator$denominator);
}

function 
GCD ($a$b)
{
    while ( 
$b != 0)
      {
        
$remainder $a $b;
        
$a $b;
        
$b $remainder;
      }
    return 
abs ($a);
}

/*
DESCRIPTION
============================================================
Decimal_to_Fraction:
A simple function that converts numbers with decimal
remainders to numbers with fractional remainders.

Includes a function to find the greatest common denominator.
============================================================

CREDITS
============================================================
Author: J. A. Greant ( zak@nucleus.com )
Version 1: June 9, 2000
============================================================

NOTICES
============================================================
If you:
    Modify this code and want to share your changes :)
    Find a bug
    Have other questions or comments

Please write:
    Zak Greant (zak@nucleus.com)
============================================================

USAGE EXAMPLES
============================================================
print Decimal_to_Fraction (1.2); // Should output 1 1/5

============================================================

COPYRIGHT
============================================================
Copyright (c) 2000 J. A. Greant ( zak@nucleus.com )
All rights reserved.

This function is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General
Public License as published by the Free Software Foundation;
either version 2.1 of the License, or (at your option) any
later version.

This function is distributed in the hope that it will be
useful,but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the GNU Lesser General Public License for more
details.

You should have received a copy of the GNU Lesser General
Public License along with this function; if not, write to
the:
    Free Software Foundation, Inc.
    59 Temple Place, Suite 330
    Boston, MA
    02111-1307 USA
    http://www.gnu.org/
============================================================
*/
?>


Usage Example




Rate This Script





Search



This Category All Categories