`
Par2: Decimal to fraction 2011-05-05 -- Geoff Robinson as others have stated to convert a fraction to a decimal just divide the numerator by the denominator. going the other way is trickier 8-) I wrote the following seven years ago (based on C code I had written back in June 1992) when the question came up in a newsgroup, and have tweaked it a bit today... it is based on Euclid's algorithm HTH Geoff R !-------------------------------------------------------------------------- VitCreateFraction FUNCTION (STRING p:Str) ! Written by Geoff Robinson, Vitesse Information Systems P/L, vitesse@mira.net ! Date: 4 May 2004 (tweaks to allow for negatives seven years later on 5&6 May 2011) ! - Assumes passed string holds valid number ! Feel free to use at own risk! L:Len LONG,AUTO i LONG,AUTO u LONG,AUTO v LONG,AUTO Numerator LONG Denominator LONG,AUTO WholeNumber STRING(32) DecPoint EQUATE('.') ! some countries may use a comma instead of dot L:Negative BYTE CODE p:Str = left(p:Str) L:Len = len(clip(p:Str)) if L:Len if p:Str[L:Len] = '-' ! allow for trailing negative L:Negative = TRUE p:Str[L:Len] = ' ' end if p:Str[1] = '-' ! allow for leading negative L:Negative = TRUE p:Str[1] = ' ' p:Str = left(p:Str) end if L:Negative then L:Len = len(clip(p:Str)). ! adjust length end if ~L:Len then return(''). ! blank string or only negative sign(s) passed over... i = instring(DecPoint,p:Str,1,1) !find the decimal point if ~i ! no decimal point found WholeNumber = p:Str else if i > 1 WholeNumber = p:Str[1 : i - 1] ! get whole number end if i < L:Len Numerator = p:Str[i + 1 : L:Len] ! get decimal fraction digits for the numerator end end if ~Numerator ! no decimal fraction to work with eg. '1.000' return(choose(~L:Negative,'','-') & clip(WholeNumber)) end Denominator = '1' & all('0',L:Len - i) ! get the initial denominator v = Numerator u = Denominator ! get the greatest common divisor based on Euclid's algorithm LOOP u = u % v if ~u then break. ! swap u and v i = u u = v v = i END!loop return( choose(~L:Negative,'','-') & | choose(WholeNumber <> 0,clip(WholeNumber) & ' ','') & | Numerator/v & '/' & Denominator/v ) Printed November 23, 2024, 5:14 pm This article has been viewed/printed 35222 times. |