Search code examples
pythonfractions

Convert decimal to a mathematical multiple fractions of 1/4 in Python


I want to compute a cup size based on a weight. One cup is defined as 240gr weight. I need to get the number of cups of a weight x in gr (decimal number), in the mathematical multiple fraction of 1/4. Result should be a string.

So, possible values should be limited to: 0, 1/4, 1/2, 3/4, 1, 1 1/4, 1 1/2, 1 3/4, 2 and so on.

Examples:

x = 130.3

cup_size: 1/2

x = 10

cup_size: 0

x = 310

cup_size: 1 1/4

How can I implement this in python? I was reading the Fractions module but I can't find something as I need.

As requested by Nathaniel, I'm not sure how to solve this math thing in python. I think it could exists a method in a library to do that. That's why I'm asking here.

So far, what I've tried is to convert with as_integer_ratio method:

weight = 351
unit = 240
weight_to_convert = int(round(weight/unit))
print(weight_to_convert.as_integer_ratio())

But this is not working, is just giving me the value as the nearest integer fraction.


Solution

  • The following might nudge you in the right direction:

    def cups(val):
        full, quarter = divmod(val // 60, 4)
        if not (full or quarter):
            return "0"
        f = f"{full:.0f}" if full else ""
        if quarter:
            if quarter == 2:
                f += " 1/2"
            else:
                f += f" {quarter:.0f}/4" 
        return f.strip()
    
    >>> cups(130)
    '1/2'
    >>> cups(310)
    '1 1/4'
    >>> cups(10)
    '0'
    

    Some docs: