Truncate to three decimals in Python

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

    Use the decimal module. But if you must use floats and still somehow coerce them into a given number of decimal points converting to string an back provides a (rather clumsy, I'm afraid) method of doing it.

    >>> q = 1324343032.324325235 * 1000 / 1000
    >>> a = "%.3f" % q
    >>> a
    '1324343032.324'
    >>> b = float(a)
    >>> b
    1324343032.324
    

    So:

    float("%3.f" % q)
    

提交回复
热议问题