Python Forum

Full Version: How to use a variable in Python (2.x) to define decimal part?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 (due to security guidelines, only Python 2.x approved for use)?

Thanks for your guidance
Use format to make a format string.
from math import pi

for i in range(10):
    fmt = '%%0.%df' %i
    print(fmt % pi)
Remember the format specifier is just a string (like "0.2f"), so you can use any method you might otherwise use to create the string dynamically.

import math

for decimals in range(2,5):
    specifier = "." + str(decimals) + "f"
    print format(math.pi, specifier)
Output:
3.14 3.142 3.1416
The precision can be passed as an argument in str.format()
# python >= 2.6
rabbits = {
    "flopsy" : 1.0/3, "mopsy" : 576.0/7, "cotton tail": .76/5, "peter": 300000.0/37,
}

nwidth = 1 + max(len(name) for name in rabbits)

for name in sorted(rabbits):
    # the floating point precision is passed as argument to format
    print("{name:{namewidth}}:{score:>10.{precision}f}".format(
          name = name, score = rabbits[name],
          namewidth = nwidth, precision = 2))
Output:
cotton tail : 0.15 flopsy : 0.33 mopsy : 82.29 peter : 8108.11
(May-06-2021, 07:06 AM)Gribouillis Wrote: [ -> ]The precision can be passed as an argument in str.format()
# python >= 2.6
rabbits = {
    "flopsy" : 1.0/3, "mopsy" : 576.0/7, "cotton tail": .76/5, "peter": 300000.0/37,
}

nwidth = 1 + max(len(name) for name in rabbits)

for name in sorted(rabbits):
    # the floating point precision is passed as argument to format
    print("{name:{namewidth}}:{score:>10.{precision}f}".format(
          name = name, score = rabbits[name],
          namewidth = nwidth, precision = 2))
Output:
cotton tail : 0.15 flopsy : 0.33 mopsy : 82.29 peter : 8108.11

Thanks. I tried. t worked. This is what I was expecting.