HS Banner
Back
Convert decimal to fraction and fraction to decimal

Author: Admin 02/13/2022
Language: Visual Basic .NET
Views: 344
Tags: fraction decimal convert


Description:

Here's two functions I found in the wild that will convert a decimal to fraction and a fraction to decimal

Article:

''' <summary>
    ''' Converts Decimal To Fraction
    ''' </summary>
    ''' <param name="_Decimal"></param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Shared Function DecimalToFraction(ByVal _Decimal As Double) As String
        Register.timer1.Start()
        Dim df As Double
        Dim lUpperPart As Long
        Dim lLowerPart As Long

        lUpperPart = 1
        lLowerPart = 1

        df = lUpperPart / lLowerPart
        While (df <> _Decimal)
            If (df < _Decimal) Then
                lUpperPart = lUpperPart + 1
            Else
                lLowerPart = lLowerPart + 1
                lUpperPart = CLng(_Decimal * lLowerPart)
            End If
            df = lUpperPart / lLowerPart
        End While
        Return CStr(lUpperPart) & "/" & CStr(lLowerPart)
    End Function

    ''' <summary>
    ''' Converts Fraction To Decimal
    ''' </summary>
    ''' <param name="Fraction"></param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Shared Function FractionToDecimal(ByVal Fraction As String) As String
        Register.timer1.Start()
        Dim decimalVal As String = "0"
        Dim upper As Decimal = 0
        Dim lower As Decimal = 0
        Dim remain As Decimal = 0
        If Fraction.IndexOf("/") <> -1 Then

            'End If < ----Extra End if
            If Fraction.IndexOf(" ") <> -1 Then
                remain = CType(Fraction.Substring(0, Fraction.IndexOf(" ")), Decimal)
                Fraction = Fraction.Substring(Fraction.IndexOf(" "))
            End If
            upper = CType(Fraction.Substring(0, Fraction.IndexOf("/")), Decimal)
            lower = CType(Fraction.Substring(Fraction.IndexOf("/") + 1), Decimal)
            decimalVal = (remain + (upper / lower)).ToString
        End If
        Return decimalVal
    End Function



Back
Comments
Add Comment
There are no comments yet.