4

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?

Watarap
  • 307
  • 3
  • 11

4 Answers4

3

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.

Netwave
  • 40,134
  • 6
  • 50
  • 93
2

I think that's more Pythonic way:

from decimal import Decimal, ROUND_DOWN
Decimal(65.4545).quantize(Decimal('.0'), rounding=ROUND_DOWN)
Surrerstry
  • 21
  • 3
1

I think you could use round expression:

>>> a = [3.5, 43.689, 113.225, 65.4545]
>>> [float(Decimal(b).quantize(decimal.Decimal('.0'), rounding=decimal.ROUND_DOWN)) for b in a]
[3.5, 43.6, 113.2, 65.4]

I hope this help you ;)

Dayana
  • 1,500
  • 1
  • 16
  • 29
1

int rounds towards zero if that is what you want:

a = [3.5, 43.689, 113.225, 65.4545]
[int(x * 10) / 10 for x in a]

Output:

[3.5, 43.6, 113.2, 65.4]
Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56