How to Keep Trailing Zeroes in Python

When working with numbers in Python, a common problem encountered is the trailing zeroes being automatically removed. This can sometimes lead to confusion or errors during computations. In this tutorial, we will explore ways to keep these important trailing zeros in Python. We shall be using a function called format().

Step 1: Understanding the Problem

Let’s consider an example to understand the problem. Below is a simple code snippet.

The output removes the trailing zeroes:

130.9

Step 2: Implementing a Solution Using the format() Function

To retain the trailing zeroes in Python, one approach is to employ string formatting. We can do so using Python’s in-built format() function.

Now, the output keeps trailing zeroes:

130.900

Step 3: Explaining the Solution

The format() function takes two arguments. The first is the number you want to format, and the second one is a string detailing how you want it formatted.

Our formatting string ‘.3f’ means we want a floating-point number with three digits after the decimal point.

So, ‘.3f’ is passed as an argument to retain three digits after the dot (even if they are zeroes).

Full Code

130.9
130.900

Conclusion

In this tutorial, we have learned how Python automatically removes trailing zeroes in numbers and how to retain these trailing zeroes using the format() function. This technique is beneficial for precise calculations and data representation. Keep practicing and exploring more functionality with Python’s built-in functions. Happy Learning!