def clamp(value, target_format, min_value=None, max_value=None):
    """
    Clamps a value inside a range (defined by an optional min_value and max_value)
    and converts the result to a target format.
    """
    if min_value is not None:
        value = max(value, min_value)
    if max_value is not None:
        value = min(value, max_value)

    return target_format(value)