Round floats down in Python to keep one non-zero decimal only

Given that all of the floats are positive you could convert them to strings and use slicing like this.

def round(num):
    working = str(num-int(num))
    for i, e in enumerate(working[2:]):
        if e != '0':
            return int(num) + float(working[:i+3])

list_num = [0.41, 0.093, 0.002, 1.59, 0.0079, 0.080, 0.375]
new_list = [round(x) for x in list_num]
print new_list

prints

[0.4, 0.09, 0.002, 1.5, 0.007, 0.08, 0.3]

If there could be floats in the list with no non-zero values after the decimal you will need to add a simple check to handle that.


You could use logarithms to work out how many leading zeroes there are, then you need a way to round down. One way is to use floor like so:

import math

list_num = [0.41, 0.093, 0.002, 1.59, 0.0079, 0.080, 0.375, 0, 10.1, -0.061]


def myround(n):
    if n == 0:
        return 0
    sgn = -1 if n < 0 else 1
    scale = int(-math.floor(math.log10(abs(n))))
    if scale <= 0:
        scale = 1
    factor = 10**scale
    return sgn*math.floor(abs(n)*factor)/factor


print [myround(x) for x in list_num]

Output:

[0.4, 0.09, 0.002, 1.5, 0.007, 0.08, 0.3]

I'm not sure how you want to handle negative numbers and numbers greater than 1, this rounds negative numbers up and numbers greater than 1 to 1dp.


Formatting your float numbers to scientific notation can help; then converting back to float types should achieve what you want. Try something like:

eval("%.0e" % (.03))
eval("%.0e" % (.034))
eval("%.0e" % (.0034))