If you just need to control the accuracy of the format
pi = 3.14159265
format(pi, '.3f')
format(pi, '.1f')
format(pi, '.10f')
If you need to control precision in floating point arithmetic
import decimal
decimal.getcontext().prec=4 #4 precision in total
pi = decimal.Decimal(3.14159265)
pi**2 #print Decimal('9.870') whereas '3.142 squared' would be off
- edit -
Without "rounding", thus trimming the number
import decimal
from decimal import ROUND_DOWN
decimal.getcontext().prec=4
pi*1 #print Decimal('3.142')
decimal.getcontext().rounding = ROUND_DOWN
pi*1 #print Decimal('3.141')
source
share