Seth Koberg Seth Koberg -5 years ago 208
Python Question

Rounding a number in python but keeping ending zeros

I've been working on a script that takes data from an XLS spreadsheet, rounds the numbers, and removes the decimal point, ex: 2606.89579999999 becomes 26069; However, I need the number to round to two decimal places even if there would be a trailing zero, so 2606.89579999999 should become 260690.

I currently have it so

takes the data from the cell in excel, and rounds it to two decimal places (
i = round(i, 2)
) which gives me the single decimal point in the above example.

I've tried figuring out how to get this to work with
, but I can't seem to get it working.

All other numbers that get rounded, if the rounded value doesn't end in '0', work fine with
round(i, 2)
but if the numbers just so happen to end in *.x0, that 0 gets dropped off and messes with the data.

Answer Source

As you are talking about trailing zeros, this is a question about representation as string, you can use

>>> "%.2f" % round(2606.89579999999, 2)

Or use modern style with format function:

>>> '{:.2f}'.format(round(2606.89579999999, 2))

and remove point with replace or translate (_ refers to result of previous command in python console):

>>> _.translate(None, '.')

Note that rounding is not needed here, as .2f format applyies the same rounding:

>>> "%.2f" % 2606.89579999999

But as you mentioned excel, you probably would opt to roll your own rounding function, or use decimal, as float.round can lead to strange results due to float representation:

>>> round(2.675, 2)
>>> round(2606.89579999999, 2)

With decimal use quantize:

>>> from decimal import *
>>> x = Decimal('2606.8950000000001')
# Decimal('2606.8950000000001')
>>> '{}'.format(x.quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN))

That, for your original task, becomes:

>>> x = Decimal('2606.8950000000001')
>>> int((x*100).quantize(1, rounding=ROUND_HALF_EVEN))

And the reason of strange rounding comes to the front with Decimal:

>>> x = Decimal(2606.8950000000001)
# Decimal('2606.89499999999998181010596454143524169921875') # internal float repr
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download