Add zeros to a float after the decimal point in Python

I've had problems with using variables in f strings. When all else fails, read the manual :)

"A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the quoting used in the outer formatted string literal."

https://docs.python.org/3/reference/lexical_analysis.html#f-strings

Case in point:

my_number = 90000
zeros = '.2f'

my_string = f"{my_number:,{zeros}}"

print (my_string)
90,000.00

my_string = f'{my_number:,{zeros}}'

will not work, because of the single quotes.

Quotes containing the f string and the string variable used in the f string should be different.

If using single quotes for the string variable, use double quotes for the f module and vice versa.


Format it to 6 decimal places:

format(value, '.6f')

Demo:

>>> format(2.0, '.6f')
'2.000000'

The format() function turns values to strings following the formatting instructions given.


I've tried n ways but nothing worked that way I was wanting in, at last, this worked for me.

foo = 56
print (format(foo, '.1f'))
print (format(foo, '.2f'))
print (format(foo, '.3f'))
print (format(foo, '.5f'))

output:

56.0 
56.00
56.000
56.00000

Meaning that the 2nd argument of format takes the decimal places you'd have to go up to. Keep in mind that format returns string.


From Python 3.6 it's also possible to do f-string formatting. This looks like:

f"{value:.6f}"

Example:

> print(f"{2.0:.6f}")
'2.000000'