Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *