import math


def formatUnits(value, units, precision=1, useUnits=True):
	"""
	Formats the value with appropriate units to the given number of digits of precision.
	The use_units parameter exists as a convenience, to make this easier to use with
	argparse boolean flags for friendly formatting.

	:param value: int or float value to format
	:param units: list of tuples of unit names with their multipliers
	:param precision: number of digits of precision to use after the decimal
	:param useUnits: bool indicating if this function should display units
	"""
	if value is None:
		return None

	#No need to attach units to infinities
	elif math.isinf(value):
		return str(value)

	scaledValue = value
	unit = ''
	if useUnits:
		for name, multiplier in units:
			if value < multiplier:
				break

			scaledValue = float(value) / multiplier
			unit = name

	formatString = '%%.%df%%s' % precision
	return formatString % (float(scaledValue), unit)