我正在寻找一个可以将给定基数的字符串转换为十进制数字的函数。
假设函数为convert
,调用convert
应该给我以下输出
convert('3.14', base=10) ~= 3.14
convert('100.101', base=2) == 4.625
答案 0 :(得分:1)
Python已经支持。只需使用my_int = int(str, base)
答案 1 :(得分:0)
要将浮点数从一个基数转换为另一个基数,您可以将数字分成两半,分别处理整个和一部分,然后将它们重新结合在一起。
num = '100.101'
base = 2
# split into whole and part
whole = num[:num.index('.')]
part = num[num.index('.') + 1:]
# get the logarithmic size of the part so we can treat it as a fraction
# e.g. '101/1000'
denom = base ** len(part)
# use python's built-in base conversion to convert the whole numbers
# thanks @EthanBrews for mentioning this
b10_whole = int(whole, base=base)
b10_part = int(part, base=base)
# recombine the integers into a float to return
b10_num = b10_whole + (b10_part / denom)
return b10_num
感谢其他回答者@EthanBrews提到整数内容已经内置。不幸的是,float
存在相同的构造。