Truncate to three decimals in Python

后端 未结 20 2491
故里飘歌
故里飘歌 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:35

    How about this:

    In [1]: '%.3f' % round(1324343032.324325235 * 1000 / 1000,3)
    Out[1]: '1324343032.324'
    

    Possible duplicate of round() in Python doesn't seem to be rounding properly

    [EDIT]

    Given the additional comments I believe you'll want to do:

    In : Decimal('%.3f' % (1324343032.324325235 * 1000 / 1000))
    Out: Decimal('1324343032.324')
    

    The floating point accuracy isn't going to be what you want:

    In : 3.324
    Out: 3.3239999999999998
    

    (all examples are with Python 2.6.5)

提交回复
热议问题