How To Remove Zeros In Float In Python

Float is a data type in Python that represents floating point numbers. It has two components – the integer component and the decimal component.

Sometimes, when working with floats, you may need to remove trailing zeros from them. In this tutorial, we will go over the steps to remove zeros in float in Python.

Steps:

  1. Convert the float to a string using the str() function.
  2. Using regular expressions, remove trailing zeros and the decimal point if there are no significant digits after it.
  3. Convert the string back to a float using the float() function.

Here’s the code:

Let’s break it down:

We start by importing the regular expressions module re. We define a function remove_zeros that takes a float and returns a float. Inside the function, we first convert the float to a string using the str() function.

We then use re.sub() to replace trailing zeros and the decimal point if there are no significant digits after it. The regular expression we use is explained below:

  • r”(\.\d*?[1-9])?[0]*$” – this matches the decimal point and any trailing zeros. The (.\d*?[1-9])? part matches the decimal point and any significant digits after it. The ? after it makes it optional. The [0]*$ part matches any remaining zeros at the end of the string.
  • r”\1″ – this replaces the matched string with the decimal point and any significant digits after it. The \1 refers to the matched group in the regular expression.

Finally, we convert the resulting string back to a float using the float() function and return it.

Let’s test our function:

Conclusion:

In this tutorial, we went over the steps to remove zeros in float in Python. We used regular expressions to replace trailing zeros and the decimal point if there are no significant digits after it. We then converted the resulting string back to a float. We also provided a code example that you can use in your own projects.

Full Code: