Truncate to three decimals in Python

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

    I am trying to generate a random number between 5 to 7 and want to limit it to 3 decimal places.

    import random
    
    num = float('%.3f' % random.uniform(5, 7))
    print (num)
    
    0 讨论(0)
  • 2020-11-27 06:51
    a = 1.0123456789
    dec = 3 # keep this many decimals
    p = 10 # raise 10 to this power
    a * 10 ** p // 10 ** (p - dec) / 10 ** dec
    >>> 1.012
    
    0 讨论(0)
提交回复
热议问题