Python Float Decimal to Octal

Problem Formulation: Given a float number. How to convert it to octal representation?

Examples: Consider the following desired conversions from float decimal numbers to their converted float octal numbers.

input:     3.14
output:    3.1075

input:     0.01
output:    0.005

input:     12.325
output:    14.246

You can play with some examples here:

Decimal to Octal converter (float)
Click to play with the converter tool.

Solution: The following code function float_to_octal() takes one float argument x to be converted and one optional argument num_digits that defines the number of digits of the converted octal float. It returns the converted octal as a float value.

The idea is to first convert the whole part of the float first—e.g., 3 for 3.14—and then convert the fractional part after the decimal digit. You loop over each digit and determine its corresponding octal digit that you collect in the list variable digits.

Finally, you convert the list of digits to the resulting octal number using the string.join() and format() functions.

def float_to_octal(x, num_digits = 4):
    '''Converts a float number x to an float octal number.'''

    whole = int(x)
    fraction = (x - whole) * 8

    # Convert first digit
    digit = int(fraction)
    fraction = (fraction - digit) * 8
    digits = [str(digit)]

    # Convert remaining digits
    i = 1
    while fraction and i < num_digits:
        digit = int(fraction)
        fraction = (fraction - digit) * 8
        digits.append(str(digit))
        i += 1
        
    return float("{:o}.{}".format(whole, "".join(digits)))

print(float_to_octal(3.14))
print(float_to_octal(0.01))
print(float_to_octal(12.325))

Output: The following is the output of the function calls on the decimal numbers 3.14, 0.01, and 12.325.

3.1075
0.005
14.2463

Here’s another strategy to convert the decimal float 3.14 to an octal number:

Convert float to octal algorithm

To improve your Python skills, join our free email academy (we have cheat sheets ;)):

References: