0

I have a list:

ls = [1.0, 2.11, 3.981329, -15.11]

I want to add zeros to decimal places of each element so that all values have the same length as the value that has maximum length. So the output should be:

[1.000000, 2.110000, 3.981329, -15.110000]

How can I do this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Programmer
  • 306
  • 2
  • 8
  • 1
    You will have to use strings. – PM 77-1 Apr 05 '22 at 20:36
  • Does this answer your question? [How to format a floating number to fixed width in Python](https://stackoverflow.com/questions/8885663/how-to-format-a-floating-number-to-fixed-width-in-python) – mkrieger1 Apr 05 '22 at 21:27
  • And: https://stackoverflow.com/questions/6189956/easy-way-of-finding-decimal-places – mkrieger1 Apr 05 '22 at 21:28

2 Answers2

1

Here's an alternative solution. Note that the nums will be strings:

ls = [1.0, 2.11, 3.981329, -15.11]

dps = lambda x: len(x) - x.index(".") - 1

max_dp = max([dps(str(i)) for i in ls])

new_ls = [f"%.{max_dp}f"%i for i in ls]

print(new_ls)

Output:

['1.000000', '2.110000', '3.981329', '-15.110000']
Emmanuel
  • 245
  • 2
  • 5
0

You can easily output to a desired number of decimal places,

print("["+", ".join(f"{el:.8f}" for el in ls)+"]")

using f-strings.

The value of getting the maximum number of visible decimal places is something you might want to consider carefully - it isn't obvious why you would do that in a simulated raw output like this. You can get a suitable number by a string analysis but it isn't pretty.

dp = 0
for el in ls:
    op = str(el)
    if "." in op:
        dpi = len(op)-1 - op.find(".")
        if dpi > dp: dp = dpi
print("["+", ".join(f"{el:.{dp}f}" for el in ls)+"]")
Joffan
  • 1,485
  • 1
  • 13
  • 18