5

Using %-formatting, I can round the number of decimal cases in a string:

pi = 3.14159265
print('pi = %0.2f' %pi)

And in output(in terminal) this would give me:

pi = 3.14

Can I use f-strings do this task? This feature has been added in Python 3.6

1

3 Answers 3

6

Include the type specifier in your format expression

format specifier:

f'{value:{width}.{precision}}'

example:

# Formatted string literals
x = 3.14159265
print(f'pi = {x:.2f}')
Sign up to request clarification or add additional context in comments.

1 Comment

in latest 3.8 you can even pi = 3.14159265; print(f'{pi =:.2f}')
6

Yes. See the Format Specification Mini-language:

>>> pi = 3.14159265
>>> print(f'{pi:.2f}')
3.14

Comments

1

Of course you can do this. The code section would be

pi = 3.14159265
print(f"{pi:.2f}")

Output: 3.14

if you want to print 3 decimal point then

pi = 3.14159265
print(f"{pi:.3f}")

Output: 3.142

You can also use .format method to do this job. like this:

pi = 3.14159265
print("{:.2f}".format(pi))

Output: 3.14

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.