[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Question about Decimal and rounding

Hi all

I have an object which represents a Decimal type.

It can receive input from various sources. It has to round the value to a 
particular scale factor before storing it. The scale factor can vary, so it 
has to be looked up every time, which is a slight overhead. I thought I 
could speed it up a bit by checking first to see if the value has any 
decimal places. If not, I can skip the scaling routine.

This is how I do it -

    s = str(value)
    if '.' in s:
        int_portion, dec_portion = s.split('.')
        is_integer = (int(int_portion) == value)
        is_integer = True

It assumes that the value is in the form iii.ddd or just iii. Today I found 
the following value -


which does not match my assumption.

It happens to work, but I don't understand enough about the notation to know 
if this is reliable, or if there are any corner cases where my test would 

I suspect that my test is a case of premature optimisation, and that I might 
as well just scale the value every time. Still, I would be interested to 
know if this could be a problem, or if there is a better way to do what I 

Thinking aloud, maybe this is a better test -

    is_integer = (value == value.quantize(0))


Frank Millman