Rounding a number in Python but keeping ending zeros

前端 未结 3 912
悲&欢浪女
悲&欢浪女 2020-12-05 00:07

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

3条回答
  •  渐次进展
    2020-12-05 01:01

    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
    

提交回复
热议问题