How to convert a string of a decimal number from any base to a decimal number? [closed]

How to convert a string of a decimal number from any base to a decimal number? [closed]



I'm looking to write a function that can convert a string with a given base to a decimal number.



Let's say the function is convert calling convert should give me the following output


convert


convert


convert('3.14', base=10) ~= 3.14
convert('100.101', base=2) == 4.625



Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.






SO is not a free coding site. If you are looking to write a function, please show some evidence of that. Right now it looks like you're looking to have a function written.

– Mad Physicist
Sep 15 '18 at 20:01







All your questions lack the part: what you tried so far ? None want to spend time to write code for you without seen you put effort in at least try something: write/type a variable name, name a function, define the function at least ...

– n1tk
Sep 15 '18 at 20:09





2 Answers
2



Python supports already. Simply use my_int = int(str, base)


my_int = int(str, base)



To convert floating-point numbers from one base to another, you can just break the number in half, handle the whole and the part separately, and then join them back together.


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



Thanks to the other answerer @EthanBrews for mentioning that integer stuff was already built-in. Unfortunately the same construction doesn't same to exist for float.


float

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế