Login
`
Templates, Tools and Utilities
|
||
Icetips Article
Back to article list
Search Articles
Add Comment
Printer friendly
Direct link
Par2: Decimal to Fraction 2004-05-03 -- Michael Ware I'm sure this function could be optimized a bit, but it runs fast enough for me:
RealToFraction PROCEDURE (REAL Num) ! Declare Procedure
i LONG
HldCheck LONG
BreakVal LONG
Numerator LONG
Denominator LONG
StringValue STRING(50)
CODE
StringValue = Num
i = INSTRING('.',StringValue,1,1)
IF ~i
DO ExitProc
END
StringValue = SUB(StringValue,i+1,LEN(CLIP(StringValue)))
BreakVal = LEN(clip(StringValue))
IF BreakVal > 46 ! error check for string slicing
BreakVal = 46
END
! Parse out the Numerator from the decimal
Numerator = 0
Denominator = 1
LOOP i = 1 TO BreakVal
IF StringValue[( i ):(i+3)] = '0000' THEN BREAK.
Numerator = 10*Numerator + StringValue[i]
Denominator = 10*Denominator
END
IF ~Numerator
StringValue = Num
DO EXITPROC
END
LOOP
HldCheck = Numerator
BreakVal = 1+SQRT(Denominator)
LOOP i = 2 TO BreakVal
IF (Numerator % i) = 0 AND (Denominator % i) = 0
Numerator = Numerator/i
Denominator = Denominator/i
BREAK
END
END
IF HldCheck=Numerator THEN BREAK.
END
StringValue = INT(Num) & ' ' & Numerator & '/' & Denominator
DO ExitProc
ExitProc ROUTINE
RETURN (StringValue)
Today is November 21, 2024, 8:32 am This article has been viewed 35220 times.
|
|