Mathmatical Equations

Im new to the VB language so forgive me if this sounds stupid. I am programming in Visual Studio 2005 Express Edition if it makes a difference. I have created my first program but i need it to diplay decimal values as fractions, as well as i need those fractions in simplist form.

Example: X = .8888888889
If the decimal is converted to a fraction it must be 8/9, and no other fraction.

Thanx

[410 byte] By [phousley17] at [2007-12-16]
# 1
There is no display formatter for this. You have to write the code yourself.

Marinus

MarinusHolkema at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic Language...
# 2

I'm not a math major, so I suspect you can find a much more efficient algorithm on one of the code/algorithm web sites to do what you are trying to do.

However, I took a crack at what you want to do and the following seems to work:



Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim x As Double = 8 / 9

Try
Me.Text = FractionString(x)
Catch ex As Exception
Me.Text = ex.Message
End Try

End Sub

Public Function FractionString(ByVal Fraction As Double) As String
Dim divisor As Integer
Dim dividend As Double

For divisor = 2 To Integer.MaxValue
dividend = Fraction * divisor
If Math.IEEERemainder(dividend, 1) = 0.0 Then Exit For
Next

If divisor = Integer.MaxValue Then
Throw New Exception("Unable to find a whole fraction for: " & Fraction)
Else
Return dividend.ToString & "/" & divisor.ToString
End If
End Function

DavidGuyerMS at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic Language...