Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: How do I print a float with a configurable number of decimals

I want to print some numbers and easily configure how many decimals are displayed. How do I turn something like this:

import numpy as np
x, y, z, s = np.random.random(4)
str_out = '[%0.4f,\t%0.4f,\t%0.4f,\t%0.4f]' % (x, y, z, s)
print(str_out)

and effectively replace %0.4f with a variable

I know I could achieve the same thing by truncating the values before printing them but hoping there is a more elegant solution

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can preprocess the %-style format string using str.format or f-strings:

import numpy as np

x, y, z, s = np.random.random(4)
precision = 6
# Option 1: using str.format
# strf = "[%0.{}f,\t%0.{}f,\t%0.{}f,\t%0.{}f]".format(*([precision] * 4))
# Option 2: using f-string
strf = f"[%0.{precision}f,\t%0.{precision}f,\t%0.{precision}f,\t%0.{precision}f]"
str_out = strf % (x, y, z, s)
print(str_out)  # [0.151736,      0.382490,       0.216538,       0.357179]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading