Amazing Python 3
69 subscribers
Learning Python 3 from scratch
Download Telegram
Setting precision when printing numbers using f-strings

If you print a floating-point number using f-strings, you can easily apply a for- matting requirement, for example, to print two digits after the decimal point.

import math

print(math.pi) # Default

print(f'{math.pi}') # Again, default
print(f'{math.pi:.2f}') # Two digits after the "."
print(f'{math.pi:.3f}')
print(f'{math.pi:.4f}')

In the given example, the value of π is printed a few times, first, without any additional truncation (well, it is still truncated to some default length), and then with two, three, and four digits after the decimal point.

$ python3 format-prec.py
3.141592653589793
3.141592653589793
3.14
3.142

3.1416

Also notice that the printed value is correctly rounded (i. e., 3.1416 is printed, not 3.1415).