Convert given Float value to equivalent Fraction | Java program for the above approach ; Recursive function to return gcd of a and b ; 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 String 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 String str ; Function Call
import java . util . * ; class GFG { static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static void findFraction ( String s ) { String be_deci = " " , af_deci = " " , reccu = " " ; boolean x = true , y = false , z = false ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( s . charAt ( i ) == ' . ' ) { x = false ; y = true ; continue ; } if ( s . charAt ( i ) == ' ( ' ) { z = true ; y = false ; continue ; } if ( x ) be_deci += s . charAt ( i ) ; if ( y ) af_deci += s . charAt ( i ) ; if ( z ) { for ( ; i < s . length ( ) && s . charAt ( i ) != ' ) ' ; ++ i ) reccu += s . charAt ( i ) ; break ; } } int num_be_deci = Integer . valueOf ( be_deci ) ; int num_af_deci = 0 ; if ( af_deci . length ( ) != 0 ) num_af_deci = Integer . valueOf ( af_deci ) ; int numr = num_be_deci * ( int ) Math . pow ( 10 , af_deci . length ( ) ) + num_af_deci ; int deno = ( int ) Math . pow ( 10 , af_deci . length ( ) ) ; if ( reccu . length ( ) == 0 ) { int gd = __gcd ( numr , deno ) ; System . out . print ( numr / gd + " ▁ / ▁ " + deno / gd ) ; } else { int reccu_num = Integer . valueOf ( reccu ) ; int numr1 = numr * ( int ) Math . pow ( 10 , reccu . length ( ) ) + reccu_num ; int deno1 = deno * ( int ) Math . pow ( 10 , reccu . length ( ) ) ; int res_numr = numr1 - numr , res_deno = deno1 - deno ; int gd = __gcd ( res_numr , res_deno ) ; System . out . print ( res_numr / gd + " ▁ / ▁ " + res_deno / gd ) ; } } public static void main ( String [ ] args ) { String str = "23.98(231 ) " ; findFraction ( str ) ; } }