**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.14output: 3.1075input: 0.01output: 0.005input: 12.325output: 14.246

You can play with some examples here:

**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:

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

**References:**

- https://stackoverflow.com/questions/40035361/how-do-i-convert-float-decimal-to-float-octal-binary
- https://www.rapidtables.com/convert/number/decimal-to-octal.html

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.