Truncate to three decimals in Python

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

    Okay, this is just another approach to solve this working on the number as a string and performing a simple slice of it. This gives you a truncated output of the number instead of a rounded one.

    num = str(1324343032.324325235)
    i = num.index(".")
    truncated = num[:i + 4]
        
    print(truncated)
    

    Output:

    '1324343032.324'
    

    Of course then you can parse:

    float(truncated)
    

提交回复
热议问题