简体   繁体   中英

python small floats rounding to 2 decimals

Yes, another one of these, however, I have tried a ton of the available examples and solutions and cannot seem to be able to solve my issue.

I need to measure the performance of an API call and decided to use the following:

for x in range(0, 5):
    try:
        nf=urllib.urlopen(_url)
        _start=time.time()
        page=nf.read()
        _end=time.time()
        nf.close()
        _delta=(_end - _start)
        _processingTimelist.append(_delta)
        time.sleep(1)
    except:
        _processingTimelist.append(9999)

outcome:

[5.2928924560546875e-05, 4.9114227294921875e-05, 4.887580871582031e-05, 7.510185241699219e-05, 5.1975250244140625e-05]

5.55992126465e-05

So far so good, looks like what I'm after. However now I want to submit this to a monitoring service and want to round it to 2 digits, as these are already representing a super small unit (milliseconds) and sending so many digits is just ridiculous.

I have tried a ton of these rounding methods, but I get super strange results like:

_processingTime = round(_processingTime, 3)
print _processingTime

result:
0.0

OR:

_processingTime = float("{0:.4f}".format(_processingTime))
print _processingTime

result:
0.0001

Why is that, and how to solve?

I don't care too much about precision, however I would expect for example 5.55992126465e-05 to become 5.56, or even 5.55 would be acceptable as the difference in real time units is super negligible.

You can format your number with scientific notation:

>>> '{:.2e}'.format(5.2928924560546875e-05)
'5.29e-05'

You can also convert it back into a float:

>>> float('{:.2e}'.format(5.2928924560546875e-05))
5.29e-05

Or for all your numbers:

>>> numbers = [5.2928924560546875e-05, 4.9114227294921875e-05, 4.887580871582031e-05, 
               7.510185241699219e-05, 5.1975250244140625e-05]
>>> [float('{:.2e}'.format(x)) for x in numbers]
[5.29e-05, 4.91e-05, 4.89e-05, 7.51e-05, 5.2e-05]

'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM