Reputation: 9
I am trying to make a Python function that takes a float number, and converts it to a string with its binary (considering the fractional part too, separated by a dot), but for some values -such as 0.5, 0.25, 0.10, 0.05 , 0.05, ...- it gives the following error:
line 7, in floatToBinary integerPart, fractionalPart = str((convertDecimal(fractional))*2).split(".")
ValueError: Not enough values to unpack (expected 2, got 1)
Functions:
def floatToBinary(floatNumber, decimalPlaces):
integerPart, fractionalPart = str(floatNumber).split(".")
integerPart = int(integerPart)
fractionalPart = int(fractionalPart)
result = bin(integerPart).lstrip("0b") + "."
for i in range(decimalPlaces):
integerPart, fractionalPart = str((convertDecimal(fractionalPart))*2).split(".")
fractionalPart = int(fractionalPart)
result += integerPart
return result
def convertDecimal(n):
while n > 1:
n /= 10
return n
Hope you can help me.
Upvotes: 0
Views: 41
Reputation: 5757
The function convertDecimal returns 0 when n = 0. So there is no '.' to split. You can fix that by casting the return value as float
def convertDecimal(n):
while n > 1:
n /= 10
return float(n)
Upvotes: 1