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

Advertisements

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

>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]

Leave a ReplyCancel reply