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
< ? php function decimalToBinary ( $ num , $ k_prec ) { $ binary = " " ; $ Integral = ( int ) ( $ num ) ; $ fractional = $ num - $ Integral ; while ( $ Integral ) { $ rem = $ Integral % 2 ; $ binary . = chr ( $ rem + 48 ) ; $ Integral = ( int ) ( $ Integral / 2 ) ; } $ binary = strrev ( $ binary ) ; $ binary . = ' . ' ; while ( $ k_prec -- ) { $ fractional *= 2 ; $ fract_bit = ( int ) $ fractional ; if ( $ fract_bit == 1 ) { $ fractional -= $ fract_bit ; $ binary . = chr ( 1 + 48 ) ; } else $ binary . = chr ( 0 + 48 ) ; } return $ binary ; } $ n = 4.47 ; $ k = 3 ; echo decimalToBinary ( $ n , $ k ) . " STRNEWLINE " ; $ n = 6.986 ; $ k = 5 ; echo decimalToBinary ( $ n , $ k ) ; ? >