-3

I have a function which trims trailing decimal places from integers and converts it to a string. For example trim(1.0) outputs '1'.

this is my code:

def trim(num): 
     num1 = str(num) 
     try: 
         if '.0' in num1: 
             return num1[:num1:rfind('.0')]
         return num1
     except Exception: 
         pass

While this takes care of numbers with 1 trailing decimal places perfectly, it does not work with more decimal places (such as 2.000). Is there a way to trim all of the trailing decimal places?

anticavity123
  • 111
  • 1
  • 9
  • 2
    Your question makes no sense. 2.000 is the same number as 2.0. You talk about "trailing decimal places from integers" but integers don't have decimal places. – wim Aug 24 '17 at 22:38
  • There is no such facility with internal representations. Trimmable decimal places exist only in the string representation, such as when you print the value. That's a matter of string formatting, which you can find with a simple borwser search. – Prune Aug 24 '17 at 22:51

1 Answers1

1

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'))
Arminius
  • 1,029
  • 7
  • 11