I need to us python to convert an improper fraction to a mixed number or even a float to a mixed number. My code is as follows:
from fractions import Fraction
nu
from fractions import Fraction
def convert_to_mixed_numeral(num):
"""Format a number as a mixed fraction.
Examples:
convert_to_mixed_numeral('-55/10') # '-5 1/2'
convert_to_mixed_numeral(-55/10) # '-5 1/2'
convert_to_mixed_numeral(-5.5) # '-5 1/2'
Args:
num (int|float|str): The number to format. It is coerced into a string.
Returns:
str: ``num`` formatted as a mixed fraction.
"""
num = Fraction(str(num)) # use str(num) to prevent floating point inaccuracies
n, d = (num.numerator, num.denominator)
m, p = divmod(abs(n), d)
if n < 0:
m = -m
return '{} {}/{}'.format(m, p, d) if m != 0 and p > 0 \
else '{}'.format(m) if m != 0 \
else '{}/{}'.format(n, d)
The function can be used by passing it the numerator and denominator as a number, string, or Fraction instance. Or it could be modified to take in the numerator and denominator as separate variables.