Truncate to three decimals in Python

后端 未结 20 2528
故里飘歌
故里飘歌 2020-11-27 06:20

How do I get 1324343032.324?

As you can see below, the following do not work:

>>1324343032.324325235 * 1000 / 1000
1324343032.3243253
>>i         


        
20条回答
  •  我在风中等你
    2020-11-27 06:43

    I've found another solution (it must be more efficient than "string witchcraft" workarounds):

    >>> import decimal
    # By default rounding setting in python is decimal.ROUND_HALF_EVEN
    >>> decimal.getcontext().rounding = decimal.ROUND_DOWN
    >>> c = decimal.Decimal(34.1499123)
    # By default it should return 34.15 due to '99' after '34.14'
    >>> round(c,2)
    Decimal('34.14')
    >>> float(round(c,2))
    34.14
    >>> print(round(c,2))
    34.14
    

    About decimals module

    About rounding settings

提交回复
热议问题