How to round Python Decimal instance

后端 未结 1 648
遥遥无期
遥遥无期 2021-01-19 00:35

How do I round a Python Decimal instance to a specific number of digits while rounding to the nearest decimal?

I\'ve tried using the .quantize(Decimal(\'.01\')

相关标签:
1条回答
  • 2021-01-19 00:48

    I think you need to use the decimal.ROUND_HALF_UP option to quantize to get what you want.

    >>> for x in ('3.605', '29342398479823.605', '3.604', '3.606'):
        print x, repr(Decimal(x).quantize(Decimal('.01'), decimal.ROUND_HALF_UP))
    
    3.605 Decimal('3.61')
    29342398479823.605 Decimal('29342398479823.61')
    3.604 Decimal('3.60')
    3.606 Decimal('3.61')
    
    0 讨论(0)
提交回复
热议问题