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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Mar 23 23:42:59 CET 2009

```On Mon, 23 Mar 2009 10:06:23 -0700, Mensanator wrote:

> On Mar 23, 5:48 am, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> 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?

No, the OP asked for a solution that didn't involve converting the
decimal number to a string first.

Besides, I don't believe you can specify the rounding mode unless you use
strings *wink*

>>> type(ROUND_DOWN)
<type 'str'>

>> 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.

Okay, so in other words you solved your problem rather than the OP's
problem.

> 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 moves
> the decimal point three places?

Of course it does, if you're using real numbers. If you're using floats,
no, not quite, there are rounding issues involved, and underflow.

I'm not sure why you raise this. Is this a general rant, or do you have a
specific criticism?

--
Steven

```