import math


def quantity_string(quantity, unit, computer_prefix=False):
    """Return a human-friendly string representing a quantity by adding
    prefixes and keeping the number of significant figures low.
    'computer_prefix' determines whether each prefix step represents 1024
    or 1000.

    Examples:
    >>> quantity_string(1024, "B", True)
    '1.0KB'

    >>> quantity_string(40000, "m", False)
    '40km'

    >>> quantity_string(0.01, "m", False)
    '0.010m'
    """
    if quantity == 0:
        return "0%s" % unit
    # Units like m, B, and Hz are typically written right after the number.
    # But if your unit is "file" or "image" then you'll want a space between
    # the number and the unit.
    if len(unit) > 2:
        space =  " "
    else:
        space = ""
    if computer_prefix:
        prefixes = ["", "K", "M", "G", "T"]
        prefix_multiplier = 1024
    else:
        prefixes = ["", "k", "M", "G", "T"]
        prefix_multiplier = 1000
    divisor = 1
    for p in prefixes:
        digits = int(math.log10(quantity / divisor)) + 1
        if digits <= 3:
            format = "%%.%df%s%s%s" % (max(2 - digits, 0), space, p, unit)
            return format % (float(quantity) / divisor)
        divisor *= prefix_multiplier

    # No prefix available. Go scientific.
    return "%.2e%s%s"% (quantity, space, unit)