Expressing A Repeating Decimal Number As A Fraction
Hi there!
Recently, someone asked me to come up with a small app that could simply add 2 fractions (with sums being inferior to 1) and display the result as a fraction as well (not in decimal form).
I thought this was going to be easy at first but I got stumped early on with this. Actually adding the 2 fractions is nothing but getting the result as a fraction is another matter.
For the most part I got it working using the function below which works well on decimal numbers without long repeating patterns, but on a fractions such as 1/7 with a decimal equivalent of 0.142857142857142857142857142857143 the function gracefully fails.
I guess what I need is a formula (preferably in VB) that would reduce those long repeating patterns within the numerator and getting the denominator value right before calling the function.
Again, as this sample all I'm trying to achieve is to come up with and display the 17/21 in my MessageBox:
1 2 17
-+-=-
7 3 21
Math was never my forte in school and I wish now that I would have paid a little more attention during my math class ;)
Anyway thanks in advance!
Here's what I got so far:
VB Code:
Private Sub Command1_Click()
Dim lngNumerator As Long, lngDenominator As Long, lngCommonFactor As Long
lngNumerator = 5
lngDenominator = 10
If GetCommonFactor(lngNumerator, lngDenominator, lngCommonFactor) Then
MsgBox lngNumerator & " / " & lngDenominator
End If
End Sub
Public Function GetCommonFactor(Numerator As Long, Denominator As Long, CommonFactor As Long) As Boolean
Dim lngIdx As Long
CommonFactor = 1
For lngIdx = Numerator To 2 Step -1
If Numerator Mod lngIdx = 0 Then
If Denominator Mod lngIdx = 0 Then
CommonFactor = lngIdx
Numerator = Numerator / CommonFactor
Denominator = Denominator / CommonFactor
GetCommonFactor = True
Exit For
End If
End If
Next
End Function