Convert Decimal to Fraction

DCooper

Member
Licensed User
Longtime User
I'm new so I'm sorry if this seems like a dumb question...

How do I convert a value returned like: 2.5
To this: 2-1/2

Thanks!
 

joseluis

Active Member
Licensed User
Longtime User
In this post I found a function written in VB.NET, that must be very easy to translate to b4a:

B4X:
Function GetFraction(ByVal d As Double) As String
        ' Get the initial denominator: 1 * (10 ^ decimal portion length)
        Dim Denom As Int32 = CInt(1 * (10 ^ d.ToString.Split("."c)(1).Length))

        ' Get the initial numerator: integer portion of the number
        Dim Numer As Int32 = CInt(d.ToString.Split("."c)(1))

        ' Use the Euclidean algorithm to find the gcd
        Dim a As Int32 = Numer
        Dim b As Int32 = Denom
        Dim t As Int32 = 0 ' t is a value holder

        ' Euclidean algorithm
        While b <> 0
            t = b
            b = a Mod b
            a = t
        End While

        'Get whole part of the number
        Dim Whole As String = d.ToString.Split("."c)(0)

        ' Return our answer
        Return Whole & " " & (Numer / a) & "/" & (Denom / a)
    End Function

I can't translate it now. If you need help with that and nobody does it first, I'll try tonight.

EDIT here is another possible implementation done in VB6.
 
Last edited:
Upvote 0

margret

Well-Known Member
Licensed User
Longtime User
You will have to write the code but the basics are to take the decimals length and place it over 1 plus the decimals length. Examples:

.5/10 divide by 5
.625/1000 divide by 125
.75/100 divide by 25

Now divide both top and bottom numbers with the highest common divisor. This in the first example would be 5. In the second would be 125 and in the third 25. So that gives you:

1/2
5/8
3/4

Hope this helps
 
Upvote 0
Top