
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Convert decimal fraction to binary number in C++
In this tutorial, we will be discussing a program to convert decimal fraction to a binary number.
For this we will be provided with a decimal fraction and integer ‘k’. Our task is to convert the given decimal fraction into its binary equivalent upto the given ‘k’ digits of decimal precision.
Example
#include<bits/stdc++.h> using namespace std; //converting decimal to binary number string convert_tobinary(double num, int k_prec) { string binary = ""; //getting the integer part int Integral = num; //getting the fractional part double fractional = num - Integral; //converting integer to binary while (Integral) { int rem = Integral % 2; binary.push_back(rem +'0'); Integral /= 2; } //reversing the string to get the //required binary number reverse(binary.begin(),binary.end()); binary.push_back('.'); //converting fraction to binary 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 << convert_tobinary(n, k) << "\n"; n = 6.986 , k = 5; cout << convert_tobinary(n, k); return 0; }
Output
100.011 110.11111
- Related Articles
- C program to convert decimal fraction to binary fraction
- Convert decimal to binary number in Python program
- Java Program to convert binary number to decimal number
- C++ Program To Convert Decimal Number to Binary
- Python program to convert decimal to binary number
- Java program to convert decimal number to binary value
- Java program to convert binary number to decimal value
- Haskell program to convert a decimal number into a binary number
- Convert Decimal to Binary in Java
- How do we convert binary to decimal and decimal to binary?
- C++ program to Convert a Decimal Number to Binary Number using Stacks
- How to convert a decimal into a fraction and a fraction into a decimal?
- How to Convert Binary to Decimal?
- How to Convert Decimal to Binary?
- C++ Program to Convert Binary Number to Decimal and vice-versa

Advertisements