First of all, you code is faulty. If I take your code and run this:
print(your_trim(1.1))
print(your_trim(1.0566))
print(your_trim('1cm'))
The output is:
1.1
1 <-- this is dangerous, the value is 1.0566!
1cm <-- this is not even a number
As the commenters mentioned, you may be mismatching floats and integers. As the name implies, an integer
does not have decimal places. If your goal ist to strip trailing zeros (for whatever reason) and not round a float
to an int
, you might use something like this approach:
def strip_trailing_zeroes(num):
if isinstance(num, float):
if int(num) == num:
return int(num)
else:
return num
else:
raise ValueError("Parameter is not a float")
Testing the code:
print(strip_trailing_zeroes(1.1))
print(strip_trailing_zeroes(1.0566))
print(strip_trailing_zeroes(1.000))
print(strip_trailing_zeroes('1cm'))
Returns the output:
1.1
1.0566
1
Exception with "ValueError: Parameter is not a float"
As the other commenters put it, I can't imagine of a use case for this.
What you might be after, is trimming trailing zeros from a "string representation" of a float. For this, a simple regular expression replacement is enough:
# match a decimal point, followed by one or more zeros
# followed by the end of the input
print(re.sub('\.0+$', '', '2.000'))