Decimal to Rational Convertor Visual Basic, VB.net
Language: Visual Basic.NET (VB.NET)
Compiler/IDE: Visual Studio
Module Module1 Dim n As Decimal Dim x As Double Sub Main() Console.WriteLine("Enter a decimal number") n = Console.ReadLine Do Until n / 1 = n \ 1 n *= 10 x += 1 Loop x = 10 ^ x Dim divisor As Integer = gcd(n, x) n /= divisor x /= divisor n = Convert.ToInt64(n) Console.WriteLine("The rational equivalent is " & n & "/" & x) Console.ReadLine() End Sub Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer If b Mod a = 0 Then Return a Else Return gcd(b, a Mod b) End If End Function End Module
Notes:The project first repeatedly multiplies and divides the decimal number with 10 until the fraction part becomes 0. In our example of input number "4.25", it is multiplied and divided by 10 two times and thus we get "425/100". To further simplify it, we find the GCD of the numerator and the denominator and divide them both by the GCD. In this case, GCD is 25 and thus we get our final result to be "17/4". The GCD function provided here uses a recursive algorithm. If you find it hard, you can use our project GCD of two numbers that uses a simple iterative approach.