decimal and trunkating
Peter Hansen
peter at engcorp.com
Thu Jun 2 09:44:14 EDT 2005
Timothy Smith wrote:
> i want to trunkate 199.999 to 199.99
> getcontext.prec = 2 isn't what i'm after either, all that does is E's
> the value.
> do i really have to use floats to do this?
I think you need a context with appropriate rounding set (e.g.
ROUND_FLOOR?) and then use the quantize() method with an argument with
the appropriate number of decimal places.
For example, this works, though I'm definitely not a Decimal expert and
am confident there's a more elegant approach (which might depend on more
information about what you're doing):
>>> d = decimal.Decimal('199.999')
>>> decimal.getcontext().rounding = decimal.ROUND_FLOOR
>>> d.quantize(decimal.Decimal('1.00'))
Decimal("199.99")
-Peter
(I hope this inspires someone who actually knows what he's doing with
Decimal to post an improved solution.)
More information about the Python-list
mailing list