Truncate to three decimals in Python

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

    I think the best and proper way is to use decimal module.

    import decimal
    
    a = 1324343032.324325235
    
    decimal_val = decimal.Decimal(str(a)).quantize(
       decimal.Decimal('.001'), 
       rounding=decimal.ROUND_DOWN
    )
    float_val = float(decimal_val)
    
    print(decimal_val)
    >>>1324343032.324
    
    print(float_val)
    >>>1324343032.324
    

    You can use different values for rounding=decimal.ROUND_DOWN, available options are ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP, and ROUND_05UP. You can find explanation of each option here in docs.

提交回复
热议问题