Nearest Fraction Converter

Takes the following parameters:

  • Decimal between 0 and 1
  • Integer >= 0 (Defaults to 7)

Returns the closest Fraction to the given decimal with a reduced-form denominator less than or equal to the second input.

import math
from fractions import Fraction
def percentConvert(percent, DENOM = 7):

    # Screen first input
    allowedDecimals = set()
    if (percent < 0 or percent > 1):
        raise Exception("First input must be a percent value between 0 and 1.")
    if (not isinstance(percent, float)):
        raise Exception("First input must be a decimal.")

    # Screen second input
    if (DENOM <= 0):
        raise Exception("Second input must be greater than zero.")
    if (not isinstance(DENOM, int)):
        raise Exception("Second input must be an integer.")

    # Create set of all valid fractions
    allowedDecimals = set()
    for denom in range(DENOM+1):
        for numer in range(denom):
            allowedDecimals.add(Fraction(numer, denom))
    allowedDecimals = sorted(allowedDecimals)

    # Find closest fraction to percent
    minList = []
    for fraction in allowedDecimals:
        minList.append(abs(percent-fraction))
    returnVal =  allowedDecimals[minList.index(min(minList))]
    return returnVal