Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format variable in f-string with a variable number of decimal places

I need to format the number of decimal places that a variable displays in an f-string using a variable for the number of places.

n = 5
value = 0.345
print(f'{value:.4f}') 

Instead of value.4f, I need value.nf where n is the number of decimal places to which the variable should be rounded.

like image 526
Mike C. Avatar asked Dec 03 '19 13:12

Mike C.


People also ask

How do you use a variable in an F string?

When using f-Strings to display variables, you only need to specify the names of the variables inside a set of curly braces {} . And at runtime, all variable names will be replaced with their respective values.

What is the correct way to format the decimal as a string to 2 decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you format a variable in a string in Python?

In the above example, we create the variables to be formatted into the string. Then, in the simples form, we can use {} as placeholders for the variables to be used. We then apply the . format() method to the string and specify the variables as an ordered set of parameters.

What is %d %s in Python?

%s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.


1 Answers

This should work:

n = 5
value = 0.345
print(f'{value:.{n}f}') 

Output:

0.34500
like image 94
CDJB Avatar answered Sep 28 '22 00:09

CDJB