Convert decimal fraction to binary number | Function to convert decimal to binary upto k - precision after decimal point ; Fetch the integral part of decimal number ; Fetch the fractional part decimal number ; Conversion of integral part to binary equivalent ; Append 0 in binary ; Reverse string to get original binary equivalent ; Append point before conversion of fractional part ; Conversion of fractional part to binary equivalent ; Find next bit in fraction ; Driver code
def decimalToBinary ( num , k_prec ) : NEW_LINE INDENT binary = " " NEW_LINE Integral = int ( num ) NEW_LINE fractional = num - Integral NEW_LINE while ( Integral ) : NEW_LINE INDENT rem = Integral % 2 NEW_LINE binary += str ( rem ) ; NEW_LINE Integral //= 2 NEW_LINE DEDENT binary = binary [ : : - 1 ] NEW_LINE binary += ' . ' NEW_LINE while ( k_prec ) : NEW_LINE INDENT fractional *= 2 NEW_LINE fract_bit = int ( fractional ) NEW_LINE if ( fract_bit == 1 ) : NEW_LINE INDENT fractional -= fract_bit NEW_LINE binary += '1' NEW_LINE DEDENT else : NEW_LINE INDENT binary += '0' NEW_LINE DEDENT k_prec -= 1 NEW_LINE DEDENT return binary NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4.47 NEW_LINE k = 3 NEW_LINE print ( decimalToBinary ( n , k ) ) NEW_LINE n = 6.986 NEW_LINE k = 5 NEW_LINE print ( decimalToBinary ( n , k ) ) NEW_LINE DEDENT