Converting an improper fraction to a mixed number with python

前端 未结 3 401
萌比男神i
萌比男神i 2021-01-22 21:40

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         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-22 22:18

    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.

提交回复
热议问题