Choose the number of decimal points in string interpolation

Viewed 4030

Is there a way to use a variable to decide the number of decimal points in literal string interpolation?

for example if I have something like

f'{some_float:.3f}'

is there a way to replace the 3 with a variable?

The end goal is to add data labels to a bar chart:

def autolabel_bar(rects, ax, decimals=3):
    """
    Attach a text label above each bar displaying its height
    """
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2.,
                height + 0.035,
                f'{round(height,decimals):.3f}',
                ha='center',
                va='center')

But I can't think of an easy way to replace the 3 in the string interpolation with the variable decimal.

2 Answers
Related