How can I make the Decimal class round down instead of to the nearest value?
Question:
I tried this code using the decimal
standard library module:
>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(22)/Decimal(7)
Decimal('3.14286')
It appears to have rounded the value to the nearest representable one.
How can I make it truncate instead, to give a result of 3.14285
?
Answers:
Just like you specify precision using the Decimal context you can also specify rounding rules.
from decimal import *
getcontext().prec = 6
getcontext().rounding = ROUND_FLOOR
print Decimal(22)/Decimal(7)
the result will be
3.14285
http://docs.python.org/release/3.1.5/library/decimal.html#decimal.Context
I tried this code using the decimal
standard library module:
>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(22)/Decimal(7)
Decimal('3.14286')
It appears to have rounded the value to the nearest representable one.
How can I make it truncate instead, to give a result of 3.14285
?
Just like you specify precision using the Decimal context you can also specify rounding rules.
from decimal import *
getcontext().prec = 6
getcontext().rounding = ROUND_FLOOR
print Decimal(22)/Decimal(7)
the result will be
3.14285
http://docs.python.org/release/3.1.5/library/decimal.html#decimal.Context