简体   繁体   中英

Round variable in Python 3.x

I have an application that generates these values:

[ -2.00000000e+00 -1.00000000e+00 -1.00929366e-16 1.00000000e+00]

How can I round the number -1.00929366e-16 to 0 ? what I want is if there is an x number of zeros from the right point, it substituted that value with zero.

The simplest solution is just using the built in mathematical function

round(float)

Which will return the integer component of the float if the 10ths decimal place is less than 5 and will return one more than that if the 10ths decimal place is greater than or equal to 5.

This should be all that you require instead of counting zeros.

*Note: Since you appear to have a list of values, use

[round(each_number) for each_number in list_of_floats]

to apply the rounding to each of the values.

**Note if you are going to be applying any mathematical operations to these numbers which require any measurement of variance, I would recommend that you do not round them as you usually want to avoid having an output of 0 from calculating, say, the standard deviation if you're going to be using it in a later function (This has caused me many headaches and required me to actually include minor variation in my floats to avoid errors in later calculations).

For more information see: https://docs.python.org/3/library/functions.html#round

(Recommended by Deja Vu)

Correct me if I'm wrong: you don't just want to round the value. You want to do so only if "there is a number of zeroes from the right point".

Let's say this number is 5. You don't want to round 0.001 , but you want to round 0.000001 to 0. And 1.000001 to 1. Well, you can do so by checking the distance between your number and the nearest integer, like this:

def round_special(n):
    return round(n) if abs(n-round(n)) < 1e-5 else n

print round_special(0.001)
print round_special(0.0001)
print round_special(0.00001)
print round_special(0.000001)
print round_special(1.0000099)

print map(round_special, [0.001, 0.0001, 0.00001, 0.000001, 1.0000099])

Which yields:

0.001
0.0001
1e-05
0.0
1.0
[0.001, 0.0001, 1e-05, 0.0, 1.0]

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