def sclip(x, lower=None, upper=None, keepType=False):
    """
    Clips the scalar value `x` to the interval [`lower`, `upper`].

    Each of `lower` and `upper` can be `None`, meaning no clipping. If
    `keepType` is `True`, the returned result has the same type as the input
    `x`, otherwise it has either the type of `x` (if it was not clipped) or the
    type of the `lower` or the `upper` value which was used for clipping.

    >>> sclip(-123.456, 0, 100, False)
    0

    >>> sclip(-123.456, 0, 100, True)
    0.0

    >>> sclip(123.456, 0, 100, False)
    100

    >>> sclip(123.456, 0, 100, True)
    100.0
    """

    xType = type(x)
    c = x
    if lower is not None:
        c = max(lower, c)
    if upper is not None:
        c = min(upper, c)

    if keepType:
        return xType(c)
    else:
        return c