Truncate to three decimals in Python

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

    Function

    def truncate(number: float, digits: int) -> float:
        pow10 = 10 ** digits
        return number * pow10 // 1 / pow10
    

    Test code

    f1 = 1.2666666
    f2 = truncate(f1, 3)
    print(f1, f2)
    

    Output

    1.2666666 1.266
    

    Explain

    It shifts f1 numbers digits times to the left, then cuts all decimals and finally shifts back the numbers digits times to the right.

    Example in a sequence:

    1.2666666 # number
    1266.6666 # number * pow10
    1266.0    # number * pow10 // 1
    1.266     # number * pow10 // 1 / pow10
    

提交回复
热议问题