MaxLunar MaxLunar - 3 months ago 19
Python Question

How do I convert float decimal to float octal/binary?

I have been searched everywhere to find a way to convert float to octal or binary. I know about the

. Is theres a modules which can do the same work for octal/binary values?

For example: I have a float
and I should get float octal
. Tell me, how I can do this? Thanks in advance.


Here's the solution, explanation below:

def ToLessThanOne(num): # Change "num" into a decimal <1
    while num > 1:
        num /= 10
    return num

def FloatToOctal(flo, places=8): # Flo is float, places is octal places
    main, dec = str(flo).split(".") # Split into Main (integer component)
                                    # and Dec (decimal component)
    main, dec = int(main), int(dec) # Turn into integers

    res = oct(main)[2::]+"." # Turn the integer component into an octal value
                             # while removing the "ox" that would normally appear ([2::])
                             # Also, res means result

    # NOTE: main and dec are being recycled here

    for x in range(places): 
        main, dec = str((ToLessThanOne(dec))*8).split(".") # main is integer octal
                                                           # component
                                                           # dec is octal point
                                                           # component
        dec = int(dec) # make dec an integer

        res += main # Add the octal num to the end of the result

    return res # finally return the result

So you can do print(FloatToOctal(12.325)) and it shall print out 14.246314631

Finally, if you want less octal places (decimal places but in octal) simply add the places argument: print(FloatToOctal(12.325, 3)) which returns 14.246 as is correct according to this website: