I have some code for converting a decimal to a fraction:
it works great for decimals such as 1.125, but can't handle infinite decimals such as 1/3
can anyone tell me how to adjust for fractions such as 1/3 or 1/7?
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim input As Decimal
If Decimal.TryParse(TextBox1.Text, input) Then
Dim denominator As Integer = 1
Do Until input Mod 1 = 0
input *= 10
denominator *= 10
Loop
Dim numerator As Integer = CInt(input)
Dim hcd As Integer = Enumerable.Range(2, Math.Min(numerator, denominator)).LastOrDefault(Function(x) numerator Mod x = 0 AndAlso denominator Mod x = 0)
If hcd <> 0 Then
Label2.Text = String.Format("Simplest Form: {0}/{1}", numerator \ hcd, denominator \ hcd)
Else
Label2.Text = String.Format("Simplest Form: {0}/{1}", numerator, denominator)
End If
End If
End Sub
can anyone tell me how to adjust for fractions such as 1/3 or 1/7?