I am working with currencies, and so have been using the decimal module to rule out any floating point weirdness in the following maths.
I have to add together a number of decimal amounts, find an average of them, add ten percent, and then round it to the nearest round £. I then need to do more decimal maths with the output, so it'll need to be a decimal (or an integer) so I can play with it. Adding the decimals has been fairly straightforward, but doing the rest of the maths has left me with this line:
result = decimal.Decimal(round((sum_of_items / count_of_items) * decimal.Decimal(1.1), 0))
It strikes me that this isn't particularly elegant, as I'm converting the decimal average+10% to a float just to round it off, and then turning the result back into a decimal.
Am I risking any floating point weirdness with that brief conversion back to floating point? And is there any way to achieve the same effect as round using the decimal module so I don't have to go decimal->float->decimal?
decimal.Decimal(1.1)
. Always initialize decimal constants with strings, to avoid rounding error:decimal.Decimal('1.1')
\$\endgroup\$ – user2357112 supports Monica May 8 '14 at 22:00