Function GetFractionFromDecimal(sngDecimal As Single) As String
[COLOR="Green"]' This function creates a worst-case fraction from the given decimal,
' passes that fraction to a Greatest Common Divisor calculator, executes
' the division using the returned GCD, and creates the fraction as a string
[/COLOR] Dim numerator As Long
Dim denominator As Long
Dim i As Long
If sngDecimal <= 0 Or sngDecimal >= 1 Then
[COLOR="Green"] 'only allows decimals between zero and 1[/COLOR]
GetFractionFromDecimal = "Out of range error."
Else
[COLOR="Green"] 'create the worst-case fraction: has a power of 10 in the denominator
'scaled to the length of the decimal[/COLOR]
denominator = 10 ^ (Len(Trim(sngDecimal)) - 2)
numerator = sngDecimal * denominator
[COLOR="Green"] 'calculate the Greatest Common Divisor[/COLOR]
i = GCD(numerator, denominator)
[COLOR="Green"] 'do the divisions and create the string[/COLOR]
GetFractionFromDecimal = CLng(numerator / i) & "/" & CLng(denominator / i)
End If
End Function
Private Function GCD(num As Long, den As Long) As Long
[COLOR="Green"]' This function calculates the Greatest Common Divisor
' by recursively multiplying together a series of
' Lowest Common Divisors calculated by LCD(), below[/COLOR]
Dim i As Long
[COLOR="Green"] 'get an LCD[/COLOR]
i = LCD(num, den)
If i > 1 Then
[COLOR="Green"] 'if the LCD > 1 then it might be further reduced, so recur[/COLOR]
GCD = i * GCD(num / i, den / i)
Else
[COLOR="Green"] 'recursion anchor[/COLOR]
GCD = 1
End If
End Function
Private Function LCD(num As Long, den As Long) As Long
[COLOR="Green"]' This function calcultes the Lowest Common Divisor
' by brute force. A variable i is incremented and tested.
' If it exceeds the numerator, it fails and a 1 is returned.[/COLOR]
Dim i As Long
i = 2
[COLOR="Green"] 'find the first number that divides evenly into the numerator and the denominator[/COLOR]
Do Until (den Mod i = 0 And num Mod i = 0)
i = i + 1 [COLOR="Green"] 'keep looking[/COLOR]
If i > num Then i = 1 [COLOR="Green"]'this will cause the loop to exit[/COLOR]
Loop
LCD = i
End Function