Removing Trailing Zeros in Python [duplicate]
Updated Generalized to maintain precision and handle unseen values:
import decimalimport randomdef format_number(num): try: dec = decimal.Decimal(num) except: return 'bad' tup = dec.as_tuple() delta = len(tup.digits) + tup.exponent digits = ''.join(str(d) for d in tup.digits) if delta <= 0: zeros = abs(tup.exponent) - len(tup.digits) val = '0.' + ('0'*zeros) + digits else: val = digits[:delta] + ('0'*tup.exponent) + '.' + digits[delta:] val = val.rstrip('0') if val[-1] == '.': val = val[:-1] if tup.sign: return '-' + val return val# test dataNUMS = ''' 0.0000 0 0 0 123.45000 123.45 0000 0 123.4506780 123.450678 0.1 0.1 0.001 0.001 0.005000 0.005 .1234 0.1234 1.23e1 12.3 -123.456 -123.456 4.98e10 49800000000 4.9815135 4.9815135 4e30 4000000000000000000000000000000 -0.0000000000004 -0.0000000000004 -.4e-12 -0.0000000000004 -0.11112 -0.11112 1.3.4.5 bad -1.2.3 bad'''for num, exp in [s.split() for s in NUMS.split('\n') if s]: res = format_number(num) print res assert exp == res
Output:
00123.450123.4506780.10.0010.0050.123412.3-123.456498000000004.98151354000000000000000000000000000000-0.0000000000004-0.0000000000004-0.11112badbad
You can use format strings if you want, but be aware that you might need to set your desired precision, as format strings have their own logic for this by default. Janneb suggests a precision of 17 in another answer.
'{:g}'.format(float(your_string_goes_here))
After thinking about this some more, though, I think the simplest and best solution is just to cast the string twice (as jathanism suggests):
str(float(your_string_goes_here))
Edit: Added clarification because of comment.
For the floating point numbers, you can just cast the string to a float
:
>>> float('123.4506780')123.450678
For the zero values, you can just cast those to an integer:
>>> int('0000')0
When printed, numeric values are automatically converted to strings. If you need these to actually be strings, you may simply cast them back to strings with str()
, e.g.:
>>> str(float('123.4506780'))'123.450678'