Related Articles

# Converting a Real Number (between 0 and 1) to Binary String

• Difficulty Level : Hard
• Last Updated : 17 Jun, 2021

Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print” ERROR:’

Examples:

```Input :  (0.625)10
Output : (0.101)2

Input : (0.72)10
Output : ERROR
```

Solution: First, let’s start off by asking ourselves what a non-integer number in binary looks like. By analogy to a decimal number, the binary number 0 .1012 would look like:
0. 1012 = 1 * 1/21 + 0 *1/22 + 1 * 1/23

Method 1: Multiply the decimal part by 2

To print the decimal part, we can multiply by 2 and check if 2*n is greater than or equal to 1. This is essentially “shifting” the fractional sum. That is:

```r = 210 * n;
= 210 * 0.1012;
= 1 * 1/20 + 0 *1/21 + 1 * 1/22;
= 1.012;```

If r >= 1, then we know that n had a 1 right after the decimal point. By doing this continuously, we can check every digit.

## C++

 `// C++ program to binary real number to string``#include ``#include``using` `namespace` `std;` `// Function to convert Binary real``// number to String``string toBinary(``double` `n)``{``    ``// Check if the number is Between 0 to 1 or Not``    ``if` `(n >= 1 || n <= 0)``        ``return` `"ERROR"``;` `    ``string answer;``    ``double` `frac = 0.5;``    ``answer.append(``"."``);` `    ``// Setting a limit on length: 32 characters.        ``    ``while` `(n > 0)``    ``{``        ` `        ``//Setting a limit on length: 32 characters    ``        ``if` `(answer.length() >= 32)``                ``return` `"ERROR"``;` `            ``// Multiply n by 2 to check it 1 or 0``            ``double` `b = n * 2;``            ``if` `(b >= 1)``            ``{``                ``answer.append(``"1"``);``                ``n = b - 1;``            ``}``            ``else``            ``{``                ``answer.append(``"0"``);``                ``n = b;``            ``}``        ``}``        ``return` `answer;``}` `// Driver code``int` `main()``{``    ``// Input value``    ``double` `n = 0.625;``    ` `    ``string result = toBinary(n);``    ``cout<<``"(0"``<< result <<``") in base 2"``<

## Java

 `// Java program to Binary real number to String.``import` `java.lang.*;``import` `java.io.*;``import` `java.util.*;` `// Class Reperesentation of Binary real number``// to String``class` `BinaryToString``{``    ``// Main function to convert Binary real number``    ``// to String``    ``static` `String printBinary(``double` `num)``    ``{``        ``// Check Number is Between 0 to 1 or Not``        ``if` `(num >= ``1` `|| num <= ``0``)``            ``return` `"ERROR"``;` `        ``StringBuilder binary = ``new` `StringBuilder();``        ``binary.append(``"."``);` `        ``while` `(num > ``0``)``        ``{``            ``/* Setting a limit on length: 32 characters,``               ``If the number cannot be represented``               ``accurately in binary with at most 32``               ``character  */``            ``if` `(binary.length() >= ``32``)``                ``return` `"ERROR"``;` `            ``// Multiply by 2 in num to check it 1 or 0``            ``double` `r = num * ``2``;``            ``if` `(r >= ``1``)``            ``{``                ``binary.append(``1``);``                ``num = r - ``1``;``            ``}``            ``else``            ``{``                ``binary.append(``0``);``                ``num = r;``            ``}``        ``}``        ``return` `binary.toString();``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``double` `num1 = ``0.625``; ``// Input value in Decimal``        ``String output = printBinary(num1);``        ``System.out.println(``"(0"` `+ output + ``")  in base 2"``);` `        ``double` `num2 = ``0.72``;``        ``output = printBinary(num2);``        ``System.out.println(``"("` `+ output + ``") "``);``    ``}``}`

## Python3

 `# Python3 program to binary real number to string` `# Function to convert Binary real``# number to String``def` `toBinary(n):` `    ``# Check if the number is Between 0 to 1 or Not``    ``if``(n >``=` `1` `or` `n <``=` `0``):``        ``return` `"ERROR"` `    ``answer ``=` `""``    ``frac ``=` `0.5``    ``answer ``=` `answer ``+` `"."` `    ``# Setting a limit on length: 32 characters.``    ``while``(n > ``0``):` `        ``# Setting a limit on length: 32 characters``        ``if``(``len``(answer) >``=` `32``):``            ``return` `"ERROR"` `        ``# Multiply n by 2 to check it 1 or 0``        ``b ``=` `n ``*` `2``        ``if` `(b >``=` `1``):` `            ``answer ``=` `answer ``+` `"1"``            ``n ``=` `b ``-` `1` `        ``else``:``            ``answer ``=` `answer ``+` `"0"``            ``n ``=` `b` `    ``return` `answer` `# Driver code``if` `__name__``=``=``'__main__'``:``    ``n ``=` `0.625``    ``result ``=` `toBinary(n)``    ``print``(``"(0"``, result, ``") in base 2"``)``    ``m ``=` `0.72``    ``result ``=` `toBinary(m)``    ``print``(``"("``, result, ``")"``)` `# This code is contributed by``# Sanjit_Prasad`

## C#

 `// C# program to Binary real number to String.` `using` `System;``using` `System.Text;` `// Class Reperesentation of Binary real number``// to String``class` `BinaryToString``{``    ``// Main function to convert Binary real number``    ``// to String``    ``static` `String printBinary(``double` `num)``    ``{``        ``// Check Number is Between 0 to 1 or Not``        ``if` `(num >= 1 || num <= 0)``            ``return` `"ERROR"``;` `        ``StringBuilder binary = ``new` `StringBuilder();``        ``binary.Append(``"."``);` `        ``while` `(num > 0)``        ``{``            ``/* Setting a limit on length: 32 characters,``            ``If the number cannot be represented``            ``accurately in binary with at most 32``            ``character */``            ``if` `(binary.Length >= 32)``                ``return` `"ERROR"``;` `            ``// Multiply by 2 in num to check it 1 or 0``            ``double` `r = num * 2;``            ``if` `(r >= 1)``            ``{``                ``binary.Append(1);``                ``num = r - 1;``            ``}``            ``else``            ``{``                ``binary.Append(0);``                ``num = r;``            ``}``        ``}``        ``return` `binary.ToString();``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``double` `num1 = 0.625; ``// Input value in Decimal``        ``String output = printBinary(num1);``        ``Console.WriteLine(``"(0 "` `+ output + ``") in base 2"``);` `        ``double` `num2 = 0.72;``        ``output = printBinary(num2);``    ``Console.WriteLine(``"("` `+ output + ``") "``);``    ``}``}`

## PHP

 `= 1 || ``\$n` `<= 0)``        ``return` `"ERROR"``;` `    ``\$answer` `= ``""``;``    ``\$frac` `= 0.5;``    ``\$answer` `.= ``"."``;` `    ``// Setting a limit on length: 32 characters.        ``    ``while` `(``\$n` `> 0)``    ``{``        ` `        ``//Setting a limit on length: 32 characters``        ``if` `(``strlen``(``\$answer``) >= 32)``                ``return` `"ERROR"``;` `            ``// Multiply n by 2 to check it 1 or 0``            ``\$b` `= ``\$n` `* 2;``            ``if` `(``\$b` `>= 1)``            ``{``                ``\$answer` `.= ``"1"``;``                ``\$n` `= ``\$b` `- 1;``            ``}``            ``else``            ``{``                ``\$answer` `.= ``"0"``;``                ``\$n` `= ``\$b``;``            ``}``        ``}``        ``return` `\$answer``;``}` `// Driver code` `// Input value``\$n` `= 0.625;` `\$result` `= toBinary(``\$n``);``echo` `"(0"` `. ``\$result` `. ``") in base 2\n"``;` `\$m` `= 0.72;``\$result``= toBinary(``\$m``);``echo` `"("` `. ``\$result` `. ``")"``;``    ` `// This code is contributed by mits``?>`

Output:

```(0.101)  in base 2
(ERROR) ```

Method 2

Alternatively, rather than multiplying the number by two and comparing it to 1, we can compare the number to . 5, then . 25, and so on. The code below demonstrates this approach.

## C++

 `// C++ program to Binary real number to String.``#include ``#include``using` `namespace` `std;` `// Function to convert Binary real``// number to String``string toBinary(``double` `n)``{``    ``// Check if the number is Between 0 to 1 or Not``    ``if` `(n >= 1 || n <= 0)``        ``return` `"ERROR"``;` `    ``string answer;``    ``double` `frac = 0.5;``    ``answer.append(``"."``);` `    ``// Setting a limit on length: 32 characters.        ``    ``while` `(n > 0)``    ``{``        ``// 32 char max``        ``if` `(answer.length() >= 32)``            ``return` `"ERROR"``;``    ``// compare the number to .5``        ``if` `(n >= frac)``        ``{``            ``answer.append(``"1"``);``            ``n = n- frac;``        ``}``        ``else``        ``{``            ``answer.append(``"0"``);``        ``}``        ` `        ``frac /= 2;``    ``}``    ``return` `answer;``}` `// Driver code``int` `main()``{``    ``// Input value``    ``double` `n = 0.625;``    ` `    ``string result = toBinary(n);``    ``cout<<``"(0"``<< result <<``") in base 2"``<

## Java

 `// Java program to Binary real number to String.``import` `java.lang.*;``import` `java.io.*;``import` `java.util.*;` `// Class Reperesentation of Binary real number``// to String``class` `BinaryToString``{``    ``// Main function to convert Binary real``    ``// number to String``    ``static` `String printBinary(``double` `num)``    ``{``        ``// Check Number is Between 0 to 1 or Not``        ``if` `(num >= ``1` `|| num <= ``0``)``            ``return` `"ERROR"``;` `        ``StringBuilder binary = ``new` `StringBuilder();``        ``double` `frac = ``0.5``;``        ``binary.append(``"."``);` `        ``while` `(num > ``0``)``        ``{``            ``/* Setting a limit on length: 32 characters,``               ``If the number cannot be represented``               ``accurately in binary with at most 32``               ``characters  */``            ``if` `(binary.length() >= ``32``)``                ``return` `"ERROR"``;` `            ``// It compare the number to . 5.``            ``if` `(num >= frac)``            ``{``                ``binary.append(``1``);``                ``num -= frac;``            ``}``            ``else`           `                ``binary.append(``0``);` `            ``// Now it become 0.25``            ``frac /= ``2``;``        ``}``        ``return` `binary.toString();``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``double` `num1 = ``0.625``; ``// Input value in Decimal``        ``String output = printBinary(num1);``        ``System.out.println(``"(0"` `+ output + ``")  in base 2"``);` `        ``double` `num2 = ``0.72``;``        ``output = printBinary(num2);``        ``System.out.println(``"("` `+ output + ``") "``);``    ``}``}`

## Python3

 `# Python3 program to Binary real number to String.` `# Function to convert Binary real``# number to String``def` `toBinary(n):` `    ``# Check if the number is Between``    ``# 0 to 1 or Not``    ``if` `(n >``=` `1` `or` `n <``=` `0``):``        ``return` `"ERROR"``;` `    ``frac ``=` `0.5``;``    ``answer ``=` `"."``;` `    ``# Setting a limit on length: 32 characters.    ``    ``while` `(n > ``0``):``        ` `        ``# 32 char max``        ``if` `(``len``(answer) >``=` `32``):``            ``return` `"ERROR"``;``            ` `        ``# compare the number to .5``        ``if` `(n >``=` `frac):``            ``answer ``+``=` `"1"``;``            ``n ``=` `n ``-` `frac;``        ``else``:``            ``answer ``+``=` `"0"``;``        ` `        ``frac ``=` `(frac ``/` `2``);``    ` `    ``return` `answer;` `# Driver code` `# Input value``n ``=` `0.625``;` `result ``=` `toBinary(n);``print``(``"( 0"``, result, ``") in base 2"``);` `m ``=` `0.72``;``result ``=` `toBinary(m);``print``(``"("``, result, ``")"``);` `# This code is contributed``# by mits`

## C#

 `// C# program to Binary real number to String.``using` `System;` `// Class Reperesentation of Binary``// real number to String``class` `BinaryToString``{``    ``// Main function to convert Binary``    ``// real number to String``    ``static` `string` `printBinary(``double` `num)``    ``{``        ``// Check Number is Between``        ``// 0 to 1 or Not``        ``if` `(num >= 1 || num <= 0)``            ``return` `"ERROR"``;` `        ``string` `binary = ``""``;``        ``double` `frac = 0.5;``        ``binary += ``"."``;` `        ``while` `(num > 0)``        ``{``            ``/* Setting a limit on length: 32 characters,``            ``If the number cannot be represented``            ``accurately in binary with at most 32``            ``characters */``            ``if` `(binary.Length >= 32)``                ``return` `"ERROR"``;` `            ``// It compare the number to . 5.``            ``if` `(num >= frac)``            ``{``                ``binary += ``"1"``;``                ``num -= frac;``            ``}``            ``else`       `                ``binary += ``"0"``;` `            ``// Now it become 0.25``            ``frac /= 2;``        ``}``        ``return` `binary;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``double` `num1 = 0.625; ``// Input value in Decimal``        ``String output = printBinary(num1);``        ``Console.WriteLine(``"(0"` `+ output + ``") in base 2"``);` `        ``double` `num2 = 0.72;``        ``output = printBinary(num2);``        ``Console.WriteLine(``"("` `+ output + ``") "``);``    ``}``}` `// This code is contributed by mits`

## PHP

 `= 1 || ``\$n` `<= 0)``        ``return` `"ERROR"``;` `    ``\$frac` `= 0.5;``    ``\$answer` `= ``"."``;` `    ``// Setting a limit on length: 32 characters.        ``    ``while` `(``\$n` `> 0)``    ``{``        ``// 32 char max``        ``if` `(``strlen``(``\$answer``) >= 32)``            ``return` `"ERROR"``;``            ` `        ``// compare the number to .5``        ``if` `(``\$n` `>= ``\$frac``)``        ``{``            ``\$answer``.=``"1"``;``            ``\$n` `= ``\$n` `- ``\$frac``;``        ``}``        ``else``        ``{``            ``\$answer``.=``"0"``;``        ``}``        ` `        ``\$frac` `= (``\$frac` `/ 2);``    ``}``    ``return` `\$answer``;``}` `// Driver code` `// Input value``\$n` `= 0.625;` `\$result` `= toBinary(``\$n``);``print``(``"(0"``.``\$result``.``") in base 2\n"``);` `\$m` `= 0.72;``\$result` `= toBinary(``\$m``);``print``(``"("``.``\$result``.``")"``);` `// This code is contributed``// by chandan_jnu``?>`

## Javascript

 ``

Output:

```(0.101)  in base 2
(ERROR)  ```

Both approaches are equally good; choose the one you feel most comfortable with.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
{"ft_lang_label":"__label__en","ft_lang_prob":0.5839783,"math_prob":0.9678653,"size":12092,"snap":"2021-43-2021-49","text_gpt3_token_len":3836,"char_repetition_ratio":0.15089345,"word_repetition_ratio":0.5770343,"special_character_ratio":0.37743962,"punctuation_ratio":0.17923309,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99983066,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-23T20:06:57Z\",\"WARC-Record-ID\":\"<urn:uuid:38c73a57-3bd4-49d4-8309-911024ea143e>\",\"Content-Length\":\"226100\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:27e48498-a174-4af3-a404-2099db70e6e2>\",\"WARC-Concurrent-To\":\"<urn:uuid:9f9fb5e9-6baf-4bb2-b3c8-cf595b18f88f>\",\"WARC-IP-Address\":\"23.218.216.54\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/converting-a-real-number-between-0-and-1-to-binary-string/\",\"WARC-Payload-Digest\":\"sha1:7BUM65C7ZBOX5VMHBAOHEQCVTXRPBX7I\",\"WARC-Block-Digest\":\"sha1:YGGP3A5JF3POLE4AOQ2MBYSM325AMWKN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323585768.3_warc_CC-MAIN-20211023193319-20211023223319-00524.warc.gz\"}"}