Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retaining first number after the decimal in python

I want python to do something similar to MS Excel =ROUNDDOWN (number, num_digits) . So in my example which looks like this

a = [3.5, 43.689, 113.225, 65.4545]

I tried like this:

a = [3.5, 43.689, 113.225, 65.4545]
b = [str(i).split(".") for i in a]

c = [i[0] for i in b]
d = [i[1][0] for i in b]

e = list(zip(c,d))
f = [float(".".join(i)) for i in e]

which gave an OUTPUT i need:

>>> print (f)
[3.5, 43.6, 113.2, 65.4]

Is there a better and simplest way to do the above in Python?

like image 813
Watarap Avatar asked Mar 08 '23 04:03

Watarap


1 Answers

Same way as you almost:

a = [3.5, 43.689, 113.225, 65.4545]
f = [float("{:.1f}".format(x)) for x in a]

Anyhow, have in mind that you can just work with the decimals and use the format for its representation.

You can transform then with math floor like this:

import math
f = [math.floor(x * 10)/10.0 for x in a]
print(f)

Here you have a live example.

like image 51
Netwave Avatar answered Mar 14 '23 20:03

Netwave