Truncate to three decimals in Python

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

    '%.3f'%(1324343032.324325235)

    It's OK just in this particular case.

    Simply change the number a little bit:

    1324343032.324725235

    And then:

    '%.3f'%(1324343032.324725235)
    

    gives you 1324343032.325

    Try this instead:

    def trun_n_d(n,d):
        s=repr(n).split('.')
        if (len(s)==1):
            return int(s[0])
        return float(s[0]+'.'+s[1][:d])
    

    Another option for trun_n_d:

    def trun_n_d(n,d):
        dp = repr(n).find('.') #dot position
        if dp == -1:  
            return int(n) 
        return float(repr(n)[:dp+d+1])
    

    Yet another option ( a oneliner one) for trun_n_d [this, assumes 'n' is a str and 'd' is an int]:

    def trun_n_d(n,d):
        return (  n if not n.find('.')+1 else n[:n.find('.')+d+1]  )
    

    trun_n_d gives you the desired output in both, Python 2.7 and Python 3.6

    trun_n_d(1324343032.324325235,3) returns 1324343032.324

    Likewise, trun_n_d(1324343032.324725235,3) returns 1324343032.324


    Note 1 In Python 3.6 (and, probably, in Python 3.x) something like this, works just fine:

    def trun_n_d(n,d):
        return int(n*10**d)/10**d
    

    But, this way, the rounding ghost is always lurking around.

    Note 2 In situations like this, due to python's number internals, like rounding and lack of precision, working with n as a str is way much better than using its int counterpart; you can always cast your number to a float at the end.

提交回复
热议问题