Convert given Float value to equivalent Fraction | Python3 program for the above approach ; Function to convert the floating values into fraction ; Initialize variables ; Traverse the floating string ; Check if decimal part exist ; Check if recurrence sequence exist ; Retrieve decimal part and recurrence resquence ; Traverse the string ; Convert to integer ; If no recurrence sequence exist ; Initialize numerator & denominator ; No reccuring term ; Print the result ; If reccuring term exist ; Convert reccuring term to integer ; reccu . size ( ) is num of digit in reccur term ; eq 2 - eq 1 ; Print the result ; Driver Code ; Given str ; Function Call
from math import gcd NEW_LINE def findFraction ( s ) : NEW_LINE INDENT be_deci = " " NEW_LINE af_deci = " " NEW_LINE reccu = " " NEW_LINE x = True NEW_LINE y = False NEW_LINE z = False NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' . ' ) : NEW_LINE INDENT x = False NEW_LINE y = True NEW_LINE continue NEW_LINE DEDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT z = True NEW_LINE y = False NEW_LINE continue NEW_LINE DEDENT if ( x ) : NEW_LINE INDENT be_deci += s [ i ] NEW_LINE DEDENT if ( y ) : NEW_LINE INDENT af_deci += s [ i ] NEW_LINE DEDENT if ( z ) : NEW_LINE INDENT while i < len ( s ) and s [ i ] != ' ) ' : NEW_LINE INDENT reccu += s [ i ] NEW_LINE i += 1 NEW_LINE DEDENT break NEW_LINE DEDENT DEDENT num_be_deci = int ( be_deci ) NEW_LINE num_af_deci = 0 NEW_LINE if len ( af_deci ) != 0 : NEW_LINE INDENT num_af_deci = int ( af_deci ) NEW_LINE DEDENT numr = ( num_be_deci * pow ( 10 , len ( af_deci ) ) + num_af_deci ) NEW_LINE deno = pow ( 10 , len ( af_deci ) ) NEW_LINE if len ( reccu ) == 0 : NEW_LINE INDENT gd = gcd ( numr , deno ) NEW_LINE print ( numr // gd , " / " , deno // gd ) NEW_LINE DEDENT else : NEW_LINE INDENT reccu_num = int ( reccu ) NEW_LINE numr1 = ( numr * pow ( 10 , len ( reccu ) ) + reccu_num ) NEW_LINE deno1 = deno * pow ( 10 , len ( reccu ) ) NEW_LINE res_numr = numr1 - numr NEW_LINE res_deno = deno1 - deno NEW_LINE gd = gcd ( res_numr , res_deno ) NEW_LINE print ( res_numr // gd , " ▁ / ▁ " , res_deno // gd ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "23.98(231 ) " NEW_LINE findFraction ( str ) NEW_LINE DEDENT