When I run this simple program 0.166666666666 is printed.
What do i do to make the print 0.17
i.e. what is the formatting command to truncate the string to two digits beyond the dec point??
x = (1/6)
s = str(x)
print(s)
You can use either
format
, or the formatting in f-strings. The description of it from the documentation is found in the
Format specification mini-language.
>>> x = 1/6
>>> print(x)
0.16666666666666666
>>> print(format(x, ".2f"))
0.17
>>> print(f"{x:.2f}")
0.17
oops, another issue. in the following I want to see 12.34. not 1.23+01
i.e.
x = 12.345678123456
s = format(x,".2")
print(s)
print(f"{x: 2.3f}")
12.346
Use
f-string
as shown last bye bowlofred.
>>> x = 12.345678123456
>>> print(f"The number is {x:.2f} a couple more {x:.4f}")
The number is 12.35 a couple more 12.3457
in the following, is the 3 the digits to the right of the decimal?
what does the 2 mean?
print(f"{x: 2.3f}")
12.346What if my number was 123456.345 and I want to see 123456.3
(Jan-02-2022, 01:06 AM)barryjo Wrote: [ -> ]123456.345 and I want to see 123456.3
Then is
n:.1f
>>> n = 123456.345
>>> print(f"The number with one decimal place {n:.1f}")
The number with one decimal place 123456.3
>>> print(f"The number with ten decimal place {n:.10f}")
The number with 10 decimal place 123456.3450000000
f'{value:{width}.{precision}}'
width
specifies the number of characters used in total to display.
Some more stuff with f-string
>>> n = 123456
>>> print(f"The number in binary {n:02b}")
The number in binary 11110001001000000
>>> print(f"The number in hex {n:02X}")
The number in hex 1E240
# f-strings can take any Python expressions inside the curly braces
>>> grapes = 5.20
>>> apples = 9.70
>>> print(f'The price is {apples + grapes:.2f}$')
The price is 14.90$
# Also methods eg .upper()
>>> for word in 'f-strings are cool'.split():
... print(f'{word.upper():~^20}')
...
~~~~~F-STRINGS~~~~~~
~~~~~~~~ARE~~~~~~~~~
~~~~~~~~COOL~~~~~~~~