Rounding a number in Python but keeping ending zeros

92,176

Solution 1

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

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

Or use modern style with format function:

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

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

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

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

>>> "%.2f" % 2606.89579999999
'2606.90'

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)
2.67
>>> round(2606.89579999999, 2)
2606.89

With decimal use quantize:

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

That, for your original task, becomes:

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

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

>>> x = Decimal(2606.8950000000001)
# Decimal('2606.89499999999998181010596454143524169921875') # internal float repr

Solution 2

As of Python 3.6, you can also use an f-string to inline format the number. In this case, the desired format is floating point with 2 decimal places so you would use .2f as the format specifier:

x = 2606.89579999999
x = round(x, 2)      # not strictly necessary as format will round for you
print(f'{x:.2f}')

Output:

2606.90

Solution 3

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

Solution 4

I the answers that I saw here did not satisfy me. So here my solution:

def round_with_padding(value, round_digits):
    return format(round(value,round_digits), "."+str(round_digits)+"f")

Hope you like it

Solution 5

In case you want to dynamically change the number of decimal places, you can use the modification below:

def formatNumber(n, digits):
    formatter = '{:.' + '{}'.format(digits) + 'f}'
    x = round(n, digits)
    return formatter.format(x)

x = 2606.89579999999
digits = 2

formatted_number = formatNumber(x, digits)

That way, all you have to do, it to change the digits variable. This will return:

2606.90
Share:
92,176

Related videos on Youtube

Seth Koberg
Author by

Seth Koberg

Updated on May 06, 2022

Comments

  • Seth Koberg
    Seth Koberg almost 2 years

    I've been working on a script that takes data from an Excel spreadsheet, rounds the numbers, and removes the decimal point, for example, 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 i 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 Decimal, 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.

    • Seth Koberg
      Seth Koberg over 10 years
      I think I've just figured it out - using i = ('%.2f' %i) seems to work. I'm going to test it with other numbers to verify that it works
    • shantanoo
      shantanoo over 10 years
      2606.89579999999 should become 260690 or 2606.90?
    • alko
      alko over 10 years
      @SethKoberg I updated my answer with decimal example if you somehow missed that (edited post alot to be more clear and precise)
    • iacob
      iacob over 2 years
  • Mark Dickinson
    Mark Dickinson over 10 years
    No need for the round call: the .2f will already do the rounding for you.
  • Ashwini Chaudhary
    Ashwini Chaudhary over 10 years
    %.2f already does the rounding for you, so you can also use: "%.2f" % (2606.89579999999) or format(2606.89579999999, '.2f')
  • alko
    alko over 10 years
    @MarkDickinson was not sure that it rounds exactly the same way, which in fact it does
  • Mark Dickinson
    Mark Dickinson over 10 years
    @alko: Mostly it does. :-) There are some oddities in Python 2.6 and earlier, though. But if you stick to Python 3 or Python 2.7 you're safe.
  • alko
    alko over 10 years
    @MarkDickinson i just checked with 2.7 and 3.3 cP and PyPy, and forgot 2.6 :)
  • Mark Dickinson
    Mark Dickinson over 10 years
    Bad idea. >>> int(round(0.29, 2) * 100) -> 28.
  • Kermit
    Kermit about 2 years
    py3.7.12 round(2606.89579999999, 2)==2606.9
  • j35t3r
    j35t3r about 2 years
    replace n by x, right?
  • Vasilis G.
    Vasilis G. almost 2 years
    @j35t3r you are absolutely right. Edited my answer.