What a great a question!! In python, you have floats and decimals that can be rounded. If you care about the accuracy of rounding, use decimal type. If you want to understand float type rounding issues, read this: http://docs.python.org/2/tutorial/floatingpoint.html#tut-fp-issues
All the examples use demical
The format of this file is broken into a few different approaches. each approach can be run independently It is separated by "#################################################" You would not normally format way. This is just to make it digestable.
To set the context of what we are working with.
print 16.0/7Output: 2.2857142857142856
from decimal import Decimal
# First we take a float and convert it to a decimal
x = Decimal(16.0/7)
# Then we round it to 2 places
output = round(x,2)
print outputOutput: 2.29
from decimal import Decimal, ROUND_HALF_UP
# Here are all your options for rounding:
# This one offers the most out of the box control
# ROUND_05UP ROUND_DOWN ROUND_HALF_DOWN ROUND_HALF_UP
# ROUND_CEILING ROUND_FLOOR ROUND_HALF_EVEN ROUND_UP
our_value = Decimal(16.0/7)
output = Decimal(our_value.quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
print outputOutput: 2.29
# If you use deimcal, you need to import
from decimal import getcontext, Decimal
# Set the precision.
getcontext().prec = 3
# Execute 1/7, however cast both numbers as decimals
output = Decimal(16.0)/Decimal(7)
# Your output will return w/ 6 decimal places, which
# we set above.
print outputOutput: 2.29
If we set the prec to 2, then we would have 2.3 If we set to 6, then we would have 2.28571
See here for an alternative using
__format__