Search code examples
pythonradix

Converting a float (real number) to any other base


I am attempting to create a program that takes a floating point number 9.325 base 10 for example, and then converts it into any specified base (binary, hex, ternary, octal etc...). Currently, I have a very inefficient way of doing this as I am not sure of a universal algorithm that would convert a real number base 10 into another base as at the moment I am using a different algorithm for base 2 conversion than base 8.

code (python but language doesn't necessarily matter):

def main():

    number = 9.325
    base = float(input("Enter base: "))
    
    if base == 2:
        # implement base 10 -> base 2 conversion algorithm
    else if base > 2:
        # implement base 10 -> base greater than 2 conversion algorithm

main()

I would like to know if there is a definitive algorithm that would take the number 9.325 and then convert it to any other base whether it be base 2 or base 16 to eliminate the need for a long chain of if statements. The thing that is making this tough for me is that the number is float, if it was an Integer this would be no problem. However, the only way I can find to convert a float to any other base is using a plethora of different algorithms, any help would be greatly appreciated. Thanks in advance.


Solution

  • Yes, there is a general algorithm for converting any number in one base to a number in another base. First of all, you convert the integer and fractional parts separately. It sounds like you are familiar with the algorithm to convert an integer from one base to another by repeatedly dividing by the base. You still need to do this with the integer part of a decimal number. For the fractional part of the number, the algorithm is similar but you repeatedly multiply by the base instead of divide.