def formatMem(kmem, unit=None):
    """Formats an amount of memory in human-friendly format.

    :type kmem: int
    :param kmem: amount of memory in KB
    :type unit: str
    :param unit: unit to use for formatting, if blank the unit closest in size will be used
    :rtype: str
    :return: human-friendly formatted string"""
    k = 1024
    if unit == "K" or not unit and kmem < k:
        return "%dK" % kmem
    if unit == "M" or not unit and kmem < pow(k, 2):
        return "%dM" % (kmem / k)
    return "%.01fG" % (float(kmem) / pow(k, 2))