Created
March 16, 2020 13:09
-
-
Save parvinderandroid/229438338aea45e7ae8d0929b02a9ff9 to your computer and use it in GitHub Desktop.
Python program to convert number from decimal fraction to binary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def decToBin(number, base, precision): | |
number = str(number) | |
integerPart = int( number[ : number.index(".") ] ) | |
fractionalPart = float( number[ number.index(".") : ] ) | |
output = "" | |
while integerPart != 0: | |
output = str( integerPart % base ) + output | |
integerPart //= base | |
if fractionalPart == 0: | |
return output | |
output += "." | |
while fractionalPart != 0 and precision != 0 : | |
fractionalPart *= base | |
fractionalPartString = str(fractionalPart) | |
output += fractionalPartString[ : fractionalPartString.index(".") ] | |
fractionalPart = float( fractionalPartString[ fractionalPartString.index(".") : ] ) | |
precision -= 1 | |
return output | |
number = float( input("Enter the number \n") ) | |
print( decToBin(number, 2, 10) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment