Decimal to Fraction
Posted: Mon Jan 23, 2006 10:53 pm
Code updated For 5.20+
This is for inc in reply to a post of his but I thought I'd post it here since it's a small trick.
As their results. This is not the fastest or most efficient but ... oh well 
EDIT: Updated to show "Integer Num/Denom" so the whole integer is separate from the fraction.
This is for inc in reply to a post of his but I thought I'd post it here since it's a small trick.
Code: Select all
Procedure.s ToFraction(Value.s)
HoldString.s
HoldPosition = FindString(Value, ".", 1)
;
HoldString = Mid(Value, HoldPosition + 1, Len(Value) - HoldPosition)
;
HoldLength = Len(HoldString)
;
Decimal = Val(HoldString)
;
Integer = Val(Mid(Value, 1, HoldPosition))
;
Numerator = Decimal
;
Denominator = Pow(10, HoldLength)
;
If Numerator < Denominator
;
GCD01 = Numerator
GCD02 = Denominator
;
Else
;
GCD01 = Denominator
GCD02 = Numerator
;
EndIf
;
Repeat
;
GCD03 = GCD02 % GCD01
;
If GCD03 = 0 : Break : EndIf
;
GCD02 = GCD01
GCD01 = GCD03
;
ForEver
;
Numerator / GCD01
;
Denominator / GCD01
;
HoldString = Str(Integer) + " " + Str(Numerator) + "/" + Str(Denominator)
;
ProcedureReturn HoldString
;
EndProcedure
Debug ToFraction("1.5")
Debug ToFraction("5.414561")
Debug ToFraction("1.094017094")

EDIT: Updated to show "Integer Num/Denom" so the whole integer is separate from the fraction.