简体   繁体   中英

print with f-string formatting on float - unable to get how the output is generated

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.

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 (ie 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'

The curly braces are being interpreted from the outside in, ie the outer-most braces will be replaced with the first argument of format() , ie x , while the inner-most braces will be replaced with the second argument of format() , ie 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() , ie y, then allows you to modify the significant digits with the value of y.

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM