在Python 3.4.2中将小数转换为分数

时间:2015-04-05 22:22:04

标签: python-3.x fractions

我只是想在Python中将小数转换为分数。我在stackoverflow上找到了一些答案。

How to convert a decimal number into fraction?

我尝试了这两种方法,但他们并没有为1.4作为输入工作,尽管他们的工作为0.25

1 个答案:

答案 0 :(得分:1)

  1. 将整数更改为字符串。我们称之为alpha
  2. 找到length
  3. alpha
  4. 创建两个空字符串:betagamma
  5. 从0到for-loop
  6. 初始化length
  7. alpha中的所有元素添加到beta,直到找到.

    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`
    
  8. gamma转换回int并使用您之前找到的功能。

  9. beta转换回int并将其乘以gamma
  10. 将此功能添加到您发布的功能的元组中。
  11. 全部完成!

    我在中写了这个,以便快速演示实现。

    请注意,由于我们并未简化分数,因此不会这样做。由于 paul manta 已宣布原因,我也没有使用我上面列出的模式。

    在这里,你去,

      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()
    
相关问题