Is there an easy way to format a float so that there is at least one trailing digit, but allows for as many as are present? Desired output would be below:
x = function(1)
x = '1.0'
y = function(1.1)
y = '1.1'
z = function(1.2345)
z = '1.2345'
Using '%.1f' will add the trailing zero, but it will also clip any longer values. I can probably kludge together a small function that checks if the value is an integer and adds a '.0', but that seems un-pythonic.
def function(value):
if int(value) == value:
form_string = '%i.0' % value
else:
form_string = ('%f' % value).rstrip('0')
return form_string
Thanks!
Simply convert to string and check if .
is there?
def function(value):
ret = str(value)
if '.' not in ret:
ret += '.0'
return ret
Anyway, str(float(value))
has the same effect, if you are dealing with small values (ie less than ~10 15 ).
Just to add an answer, for a fixed "I want at least one digit after the period" you just have to format it as float:
def parse(a):
return str(float(a))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.