how to convert from Decimal('1.23456789') to Decimal('1.234')

Mensanator mensanator at
Mon Mar 23 18:06:23 CET 2009

On Mar 23, 5:48 am, Steven D'Aprano <st... at REMOVE-THIS-> wrote:
> On Mon, 23 Mar 2009 01:45:53 -0700, Mensanator wrote:
> >> but you can create a helper
> >> function very easily:
> >> def round(dec, places, rounding=decimal.ROUND_HALF_UP): return
> >> dec.quantize(decimal.Decimal(str(10**-places)), rounding)
> > Still ugly. I would do this:
> >>>> a = Decimal('1.23456789')
> >>>> for i in xrange(1,6):
> >    print Context.create_decimal(Context(i,ROUND_DOWN),a)
> Well, that's hardly any less ugly.

I wouldn't say so since there are no strings attached. Didn't the
OP specifically ask for a solution that didn't involve strings?

> And it also gives different results to my function: my function rounds to
> <places> decimal places, yours to <i> digits. Very different things.

Yeah, I know all about that. I work in Environmental Remediation.
That's real science, where rounding to decimal places is strictly
forbidden, significant digits must be preserved. That means rounding
to digits. Do you know what kind of hoops I have to jump through to
get Access or Excel to round properly when doing unit conversion?

Surely you're not so maive that you think dividing by 1000 simply
the decimal point three places?

> --
> Steven

More information about the Python-list mailing list