0
x = 100.1205
y = str(x)[6]

which means y=0

When try to execute below code output is 100.

print ("{:.{}f}".format(x,y))

Can anyone tell how it is giving 100 as output.

smci
  • 32,567
  • 20
  • 113
  • 146
sre
  • 249
  • 1
  • 12

3 Answers3

3

First off, let's number the fields: the format string '{:.{}f}' is equivalent to '{0:.{1}f}'.

The argument at position 1 is y, which equals 0, so this is equivalent to '{0:.0f}' by substitution. That is, it formats the argument at position 0 (i.e. x) as a float, with 0 decimal places.

So, the result is '100', because that's x to 0 decimal places. You can try this with different values of y to see the results:

>>> '{:.{}f}'.format(100.1205, 0)
'100'
>>> '{:.{}f}'.format(100.1205, 1)
'100.1'
>>> '{:.{}f}'.format(100.1205, 2)
'100.12'
>>> '{:.{}f}'.format(100.1205, 3)
'100.121'
>>> '{:.{}f}'.format(100.1205, 4)
'100.1205'
>>> '{:.{}f}'.format(100.1205, 5)
'100.12050'
kaya3
  • 47,440
  • 4
  • 68
  • 97
0

The curly braces are being interpreted from the outside in, i.e. the outer-most braces will be replaced with the first argument of format(), i.e x, while the inner-most braces will be replaced with the second argument of format(), i.e. y. Here, x will represent the float to display, and y will represent the significant digits after the decimal place. See plenty of examples and docs here

If this is still unclear, I would break it down into single format operation first, to better understand:

>>> print ("{}".format(x))
100.1205

Now all we want to do is trim off all significant digits after the decimal point, then:

>>> print ("{:.0f}".format(x))
100

Or to trim off all but one:

>>> print ("{:.1f}".format(x))
100.1

Adding another parameter to format(), i.e. y, then allows you to modify the significant digits with the value of y.

>>> print ("{:.{}f}".format(x,y)
100
topher217
  • 1,188
  • 12
  • 35
0

x = 100.1205, y = str(x)[6]. here y = 0

first of all understand the "{:.{}f}".format(x,y). here we are using the position formatting of the string . then we can see that x is at position 0 and y is at position 1.

we can consider "{:.{}f}" it as "{value of x:{value of y}f}"

now value of x is 100 and value of y is 0 so the string will look like "{100:.{0}f}". that means that there is 0 or no digits after decimal

when print("{:.{}f}".format(x,y)) will execute it will print "100"

Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53