Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I substitute a variable in format command of python?

Tags:

python

format

My code finds an unknown (0<alpha<1), its precision depends on another parameter (dm). Finally, alpha is determined with e.g. 20 digits but depending on dm, alpha should be kept until definite (which is known during execution=njj) digit. At the end, I need to substitute njj in format command as following:

njj= 8 ;alpha= 0.0004258819580078126 # I need this alpha= 0.00042588

print('{:.njj f}'.format(alpha))

But it doesn't work!

It shows: ValueError: Format specifier missing precision

like image 295
Maryam Samadi Avatar asked Aug 11 '26 21:08

Maryam Samadi


1 Answers

this is quite a good question.

i find that this works nicely:

njj= 8
alpha= 0.0004258819580078126 # I need this alpha= 0.00042588

print(f'{alpha:.{njj}f}')

which gives this:

0.00042588

but also, you could do this:

print(round(alpha, njj))

update: As per the comments below from @Mark, the round() function produces a different number of decimal places compared to the formatted f-string method when there are trailing Zero's. So the user would need to decide which one they wanted to see.

like image 174
D.L Avatar answered Aug 14 '26 10:08

D.L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!