Converting a Real Number ( between 0 and 1 ) to Binary String | Main function to convert Binary real number to String ; Check Number is Between 0 to 1 or Not ; Setting a limit on length : 32 characters , If the number cannot be represented accurately in binary with at most 32 characters ; It compare the number to . 5. ; Now it become 0.25 ; Input value in Decimal
function printBinary ( num ) { if ( num >= 1 num <= 0 ) return " " ; let binary = " " ; let frac = 0.5 ; binary += " " ; while ( num > 0 ) { if ( binary . length >= 32 ) return " " ; if ( num >= frac ) { binary += " " ; num -= frac ; } else binary += " " ; frac = frac / 2 ; } return binary ; } let num1 = 0.625 ; let output = printBinary ( num1 ) ; document . write ( " " + output + " " + " " ) ; let num2 = 0.72 ; output = printBinary ( num2 ) ; document . write ( " " + output + " " ) ;