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 ; Swap values of left and right ; Driver code
function decimalToBinary ( num , k_prec ) { let binary = " " ; let Integral = parseInt ( num , 10 ) ; let fractional = num - Integral ; while ( Integral > 0 ) { let rem = Integral % 2 ; binary += ( String . fromCharCode ( rem + ' ' . charCodeAt ( ) ) ) ; Integral = parseInt ( Integral / 2 , 10 ) ; } binary = reverse ( binary ) ; binary += ( ' ' ) ; while ( k_prec -- > 0 ) { fractional *= 2 ; let fract_bit = parseInt ( fractional , 10 ) ; if ( fract_bit == 1 ) { fractional -= fract_bit ; binary += String . fromCharCode ( 1 + ' ' . charCodeAt ( ) ) ; } else { binary += String . fromCharCode ( 0 + ' ' . charCodeAt ( ) ) ; } } return binary ; } function reverse ( input ) { let temparray = input . split ( ' ' ) ; let left , right = 0 ; right = temparray . length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { let temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return temparray . join ( " " ) ; } let n = 4.47 ; let k = 3 ; document . write ( decimalToBinary ( n , k ) + " " ) ; n = 6.986 ; k = 5 ; document . write ( decimalToBinary ( n , k ) ) ;