How to use a variable in Python (2.x) to define decimal part?
=============================================================
Thanks for reviewing this thread.
I find the convention of using %.2f to set two decimal places for a float output format. I am looking a way to change the number to a variable so that the number of decimal places displayed based on input/parameter.
Eg:
"%0.2f" % 10.120
'10.12'
pv = 2 # is variable has the number of decimal places
"%0.pvf" % 10.120
'10.12'
pv = 3
"%0.pvf" % 10.120
'10.120'
OR
input_v = 445.76528
pv =2 # is variable has the number of decimal places
print(format(input_v, '.pvf'))
>> 445.76
pv = 3
print(format(input_v, '.pvf'))
>> 445.765
pv = 4
print(format(input_v, '.pvf'))
>> 445.7652
I find for Python 3.6+ we can do this with f-string style formatter:
num = 0.123456789
precision = 3
print(f"{num:.{precision}f}")
What is the equivalent on Python 2.x?
Thanks for your guidance