Skip to content

Instantly share code, notes, and snippets.

@parvinderandroid
Created March 16, 2020 13:09
Show Gist options
  • Save parvinderandroid/229438338aea45e7ae8d0929b02a9ff9 to your computer and use it in GitHub Desktop.
Save parvinderandroid/229438338aea45e7ae8d0929b02a9ff9 to your computer and use it in GitHub Desktop.
Python program to convert number from decimal fraction to binary
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