I\'m looking for a way to convert numbers to string format, dropping any redundant \'.0\'
The input data is a mix of floats and strings. Desired output:
0
str(x)[-2:] == '.0' and int(x) or x
Using Python's string formatting (use str.format() with Python 3.0):
from decimal import Decimal
def format_number(i):
return '%g' % (Decimal(str(i)))
To print a float
that has an integer value as an int
:
format = "%d" if f.is_integer() else "%s"
print(format % f)
Example
0.0 -> 0
0.1 -> 0.1
10.0 -> 10
12345678.9 -> 12345678.9
123456789.0 -> 123456789
12345678912345.0 -> 12345678912345
12345678912345.6 -> 1.23456789123e+13
1.000000000001 -> 1.0
I was dealing with a value from a json dictionary (returned by an API). All the above didnt help me so i constructed by own helper function. It truncates all the trailing zeros.
I Hope it helps someone out there
def remove_zeros(num):
nums = list(num)
indexes = (list(reversed(range(len(nums)))))
for i in indexes:
if nums[i] == '0':
del nums[-1]
else:
break
return "".join(nums)
num = "0.000000363000"
print(remove_zeros(num))
prints :
0.000000363