如何将十进制数的字符串从任何基数转换为十进制数? [关闭]

问题描述 投票:-5回答:2

我正在寻找一个函数,可以将给定基数的字符串转换为十进制数。

让我们说函数是convert调用convert应该给我以下输出

convert('3.14', base=10) ~= 3.14
convert('100.101', base=2) == 4.625
python python-3.x
2个回答
1
投票

Python已经支持了。只需使用my_int = int(str, base)


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不同。

© www.soinside.com 2019 - 2024. All rights reserved.