Convert decimal fraction to binary number | C ++ program to convert fractional decimal 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string decimalToBinary ( double num , int k_prec ) { string binary = " " ; int Integral = num ; double fractional = num - Integral ; while ( Integral ) { int rem = Integral % 2 ; binary . push_back ( rem + '0' ) ; Integral /= 2 ; } reverse ( binary . begin ( ) , binary . end ( ) ) ; binary . push_back ( ' . ' ) ; while ( k_prec -- ) { fractional *= 2 ; int fract_bit = fractional ; if ( fract_bit == 1 ) { fractional -= fract_bit ; binary . push_back ( 1 + '0' ) ; } else binary . push_back ( 0 + '0' ) ; } return binary ; } int main ( ) { double n = 4.47 ; int k = 3 ; cout << decimalToBinary ( n , k ) << " STRNEWLINE " ; n = 6.986 , k = 5 ; cout << decimalToBinary ( n , k ) ; return 0 ; }