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?

Asked By: bad_keypoints

||

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

Answered By: Eduardo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.