1

How do I get this code to always return 1 decimal for every element in the array?

import numpy as np

def mult_list_with_x(liste, skalar):
    print(np.array(liste) * skalar)

liste = [1, 1.5, 2, 2.5, 3]
skalar = 2

mult_list_with_x(liste, skalar)

I.e.: [2.0 3.0 4.0 5.0 6.0]

not [2. 3. 4. 5. 6.]

1
  • I understand. But that is sort of the question :) How is each array element converted to strings with the correct format? Can it be done in the print command - or do they have to be converted first and then printed? Commented Sep 9, 2022 at 15:34

2 Answers 2

2

You can use np.set_printoptions to set the format:

import numpy as np

def mult_list_with_x(liste, skalar):
    print(np.array(liste) * skalar)

liste = [1, 1.5, 2, 2.5, 3]
skalar = 2

np.set_printoptions(formatter={'float': '{: 0.1f}'.format})

mult_list_with_x(liste, skalar)

Output:

[ 2.0  3.0  4.0  5.0  6.0]

Note that this np printoptions setting is permanent - see below for a temporary option.
Or to reset the defaults afterwards use:

np.set_printoptions(formatter=None)
np.get_printoptions()  # to check the settings

An option to temporarily set the print options - kudos to mozway for the hint in the comments!:

with np.printoptions(formatter={'float': '{: 0.1f}'.format}):
    print(np.array(liste) * skalar)

An option to just format the print output as string:

print(["%.1f" % x for x in ( np.array(liste) * skalar)])

Output:

['2.0', '3.0', '4.0', '5.0', '6.0']

Choose an option fitting how the output should further be used.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you :) Assuming then, that you can't do it directly in the print command? (Just for curiosity)
Note that you can use numpy.printoptions as context manager for a temporary change.
2

You need to use this setup first:

float_formatter = "{:.1f}".format
np.set_printoptions(formatter={'float_kind':float_formatter})

Output

[2.0 3.0 4.0 5.0 6.0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.