Menu Close

How to format a decimal to always show 2 decimal places with Python?

Sometimes, we want to format a decimal to always show 2 decimal places with Python.

In this article, we’ll look at how to format a decimal to always show 2 decimal places with Python.

How to format a decimal to always show 2 decimal places with Python?

To format a decimal to always show 2 decimal places with Python, we can use the string format method.

For instance, we write

from math import pi

s = '{0:.2f}'.format(pi)

to call '{0:.2f}'.format with pi to return a string that has pi in rounded to 2 decimal places.

Conclusion

To format a decimal to always show 2 decimal places with Python, we can use the string format method.

Posted in Python, Python Answers