- Code: Select all
Public Function ReducedFraction(ByVal Num As Double) As String
Const HiD As Long = 64 ' Highest denominator
Dim Rf As String
Dim M As Long
Dim n As Long
Dim d As Long
M = Int(Abs(Num))
n = Round((Abs(Num) - M) * HiD, 0)
If n Then
If n = HiD Then
M = M + 1
Else
d = HiD
Do While (n Mod 2 = 0)
n = n / 2
d = d / 2
Loop
Rf = " " & CStr(n) & "/" & CStr(d)
End If
End If
M = M * Sgn(Num)
If Len(Rf) Then
If M Then Rf = CStr(M) & Rf
Else
Rf = CStr(M)
End If
ReducedFraction = Rf
End Function
You can change the Const Hid (Highest Denominator) to any value that is divisible into 2. The lowest denominator returned by the function will be the first odd number encountered after repeatedly dividing the highest denominator into 2. For example
If HiD = 48 the divisions will produce the denominators 24, 12, 6 and 3.
If HiD = 64 the divisions will produce the denominators 32, 16, 8, 4 and 2.
Note that the original decimal will be rounded to the nearest HiD. For example 0.24 will return
15/64 if HiD = 64 but
1/4 if HiD = 32, 16, 8 or 4
The following code is an example of how to call the above function from within your code:
- Code: Select all
Private Sub test()
Debug.Print ReducedFraction(13.24)
End Sub