Truncate to three decimals in Python

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

    You can use the following function to truncate a number to a set number of decimals:

    import math
    def truncate(number, digits) -> float:
        stepper = 10.0 ** digits
        return math.trunc(stepper * number) / stepper
    

    Usage:

    >>> truncate(1324343032.324325235, 3)
    1324343032.324
    

提交回复
热议问题