Smallest number to multiply to convert floating point to natural | Java program to find the smallest number to multiply to convert a floating point number into natural number . ; Finding GCD of two number ; Returns smallest integer k such that k * str becomes natural . str is an input floating point number ; Find size of string representing a floating point number . ; Below is used to find denominator in fraction form . ; Used to find value of count_after_dot ; To find numerator in fraction form of given number . For example , for 30.25 , numerator would be 3025. ; If there was no dot , then number is already a natural . ; Find denominator in fraction form . For example , for 30.25 , denominator is 100 ; Result is denominator divided by GCD - of - numerator - and - denominator . For example , for 30.25 , result is 100 / GCD ( 3025 , 100 ) = 100 / 25 = 4 ; Driver code
class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int findnum ( String str ) { int n = str . length ( ) ; int count_after_dot = 0 ; boolean dot_seen = false ; int num = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) != ' . ' ) { num = num * 10 + ( str . charAt ( i ) - '0' ) ; if ( dot_seen == true ) count_after_dot ++ ; } else dot_seen = true ; } if ( dot_seen == false ) return 1 ; int dem = ( int ) Math . pow ( 10 , count_after_dot ) ; return ( dem / gcd ( num , dem ) ) ; } public static void main ( String [ ] args ) { String str = "5.125" ; System . out . print ( findnum ( str ) ) ; } }