-3

I just wanted to convert a decimal to fractions in Python. I found some answers here on stackoverflow.

How to convert a decimal number into fraction?

I tried both the methods but they didn't worked for 1.4 as input, though they worked for 0.25

buhtz
  • 10,774
  • 18
  • 76
  • 149
  • 2
    Not all real values can be represented in floating point. Evaluating `(1.4).as_integer_fraction()` will give you `(3152519739159347, 2251799813685248)`, which is [pretty close to 1.4](https://www.wolframalpha.com/input/?i=3152519739159347+%2F+2251799813685248). If you want 100 percent precision then you'll have to avoid floats altogether and use decimals from the start. – Paul Manta Apr 05 '15 at 22:29

2 Answers2

1
  1. Change your integer into a string. Let us call this alpha
  2. Find the length of alpha
  3. Create two empty string: beta and gamma
  4. Init a for-loop from 0 to length
  5. Add all elements in alpha to beta until a . is found

    If a decimal is not found or only 0 (or any amounts of zeros), then your number is over `alpha` over 1.
    If a decimal is found, start adding the elements to `gamma`
    
  6. Convert gamma back into an int and use the function you found previously.

  7. Convert beta back into an int and multiply this by gamma.
  8. Add this to the tuple from the function you posted.

All done!

I wrote this in to quickly demonstrate an implementation.

PLEASE NOTE THAT THIS IS NOT DONE AS WE ARE NOT SIMPLIFYING THE FRACTION. THIS ALSO DOES NOT USE THE PATTERN THAT I LISTED ABOVE BECAUSE OF REASONS paul manta DECLARED.

Here ya go,

  def findFraction(string):
        from math import pow
        length      = len(string)
        c           = '{a}/{b}'.format(a=string, b=int(pow(10,length)))
        print(c)
        return c

  def finishFraction(addToNumerator, currentFraction):
        temp        = ''
        temp2       = ''
        slashFlag   = False
        for i in range(0,len(currentFraction)):
              if currentFraction[i]=='/':
                    slashFlag = True
              elif slashFlag==True:
                    temp2 =temp2+currentFraction[i]
              else:
                    temp  = temp+currentFraction[i]
        numerator   = int(temp)+(int(addToNumerator)*int(temp2))
        fraction    = str(numerator)+'/'+str(temp2)
        return fraction

  def fractionForm(number):
        alpha       = str(number)
        length      = len(alpha)
        beta        = ''
        gamma       = ''
        dotFlag     = False
        for i in range(0, length):
              if alpha[i]=='.':
                    if dotFlag==True:
                          print("SHOULD NOT HAVE TWO DECIMALS IN NUMBER")
                          assert(False)
                    dotFlag=True
              elif dotFlag==False:
                    beta=beta+alpha[i]
              else:
                    gamma=gamma+alpha[i]
        if gamma=='':
              print('{a}/{b}'.format(a=int(beta),b=1))
              return (int(beta),1)
        else:
              fraction    = findFraction(gamma)
              fraction    = finishFraction(beta,fraction)
              print(fraction)
              return fraction

  def test():
        woooo = fractionForm(1.25)
        woohoo= fractionForm(99.999)

  dtest()
T.Woody
  • 1,142
  • 2
  • 11
  • 25
0
def f(a):
    d = 0
    s = str(a)

    for i in range(len(s)):
        if s[i] == '.':
            d = len(s) - (i+1)
            break

    b = 10**d
    a*= b
    a = int(a)
    c = 1

    for j in range(2, min(a,b)+1):
        if a%j == 0 and b%j == 0:
            c = j

    a//= c
    b//= c

    print(a,'/',b)

f(float(input()))
buhtz
  • 10,774
  • 18
  • 76
  • 149
  • 6
    Please add further details to expand on your answer, such as working code or documentation citations. – Community Sep 06 '21 at 19:34