How to Display Two Decimal Places in Python

In Python, you often need to display numbers to a certain number of decimal places. This may be crucial in areas such as financial calculations, scientific computations, and anywhere precision is required.

In this tutorial, we will specifically explore how to display numbers up to two decimal places in Python. Various approaches such as using the round function, the format function, and the string format method (%) will be explained.

Step 1: Using Round Function

We can use the round() function in Python to round a number to two decimal places. Here’s a code snippet that demonstrates this:

The output of the code above will be:

13.95

Step 2: Using Format Function

The format() function allows us to format numbers. Here’s how you can use the format() function to display a number to two decimal places:

The output of the code above will be:

13.95

Step 3: Using String Format Method (%)

The formatter % is an older method for formatting strings in Python, but still quite useful for certain situations. Here’s how you can use it:

The output of the code above will be:

13.95

Full Code

Here’s the entire code snippet summarizing all 3 methods.

Conclusion

Formatting numbers to two decimal places is a common task in Python programming, especially when dealing with financial or scientific data.

In this tutorial, we have looked at three ways to accomplish this the round function, the format function, and the string format method. Always select the method that best fits your particular scenario.