You could use something like this:
def remove_trailing_zeros(x):
return str(float(x)).rstrip('0').rstrip('.')
remove_trailing_zeros(1.23) # '1.23'
remove_trailing_zeros(4.0) # '4
remove_trailing_zeros(1000) # '1000'
Normally, you would use standard string formatting options like '%2.1f' % number
or any of the other many ways to format a string. However, you would then have to specify the amount of digits you want to display but in this case the number of trailing zeros to return is variable. The '%g'
format specifier does not have this problem, but uses scientific notation and I don't know if that is what the OP wants.
The above solution converts the number to a "nicely printable string representation" (str(x)
), and then removes trailing zeros (.rstrip('0')
) and if necessary the remaining trailing period (.rstrip('.')
) (to avoid "1." as a result) using standard string methods.
Note: I added the cast to float to make sure the code works correctly for integers as well, in case anyone needs that.