Truncate to three decimals in Python

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

    Maybe python changed since this question, all of the below seem to work well

    Python2.7

    int(1324343032.324325235 * 1000) / 1000.0
    float(int(1324343032.324325235 * 1000)) / 1000
    round(int(1324343032.324325235 * 1000) / 1000.0,3)
    # result for all of the above is 1324343032.324
    
    0 讨论(0)
  • 2020-11-27 06:35

    How about this:

    In [1]: '%.3f' % round(1324343032.324325235 * 1000 / 1000,3)
    Out[1]: '1324343032.324'
    

    Possible duplicate of round() in Python doesn't seem to be rounding properly

    [EDIT]

    Given the additional comments I believe you'll want to do:

    In : Decimal('%.3f' % (1324343032.324325235 * 1000 / 1000))
    Out: Decimal('1324343032.324')
    

    The floating point accuracy isn't going to be what you want:

    In : 3.324
    Out: 3.3239999999999998
    

    (all examples are with Python 2.6.5)

    0 讨论(0)
  • 2020-11-27 06:37

    You can use an additional float() around it if you want to preserve it as a float.

    %.3f'%(1324343032.324325235)
    
    0 讨论(0)
  • 2020-11-27 06:38

    I suggest next solution:

    def my_floor(num, precision):
       return f'{num:.{precision+1}f}'[:-1]
    
    my_floor(1.026456,2) # 1.02
    
    
    0 讨论(0)
  • 2020-11-27 06:40

    Use the decimal module. But if you must use floats and still somehow coerce them into a given number of decimal points converting to string an back provides a (rather clumsy, I'm afraid) method of doing it.

    >>> q = 1324343032.324325235 * 1000 / 1000
    >>> a = "%.3f" % q
    >>> a
    '1324343032.324'
    >>> b = float(a)
    >>> b
    1324343032.324
    

    So:

    float("%3.f" % q)
    
    0 讨论(0)
  • 2020-11-27 06:40

    Maybe this way:

    def myTrunc(theNumber, theDigits):
    
        myDigits = 10 ** theDigits
        return (int(theNumber * myDigits) / myDigits)
    
    0 讨论(0)
提交回复
热议问题