Reputation: 235
Is there an elegant way to have a float→str output with eg zero or one digits?
8.5 should become '8.5', and 9.0 should become '9'.
Update. Well, to make it more precise, the way, that'll work for any float, and will output one digit save for the "integer" floats, which should be formatted as integers, id est without decimal point.
Upvotes: 0
Views: 1564
Reputation: 235
Turned out that for my use case I can use Decimal instead of float, setting it from strings, and it does the right thing™:
>>> 'value={}'.format(Decimal('5'))
'value=5'
>>> 'value={}'.format(Decimal('5.5'))
'value=5.5'
Upvotes: 1
Reputation: 164633
With Python 3.6+ you should consider formatted string literals (PEP 498):
x = 8.5
y = 9.0
z = 8.05
for i in (x, y, z):
print(f'{i:.9g}')
8.5
9
8.05
Manually, you can define a function to compare float
and int
values:
def make_str(x):
float_val = float(x)
int_val = int(float_val)
if float_val == int_val:
return str(int_val)
return str(float_val)
make_str(9.0) # '9'
make_str(8.5) # '8.5'
Upvotes: 3
Reputation: 1362
Try str.format
with "General format" as described here.
In [1]: print('{:.9g}'.format(8.5))
8.5
In [2]: print('{:.9g}'.format(9.0))
9
Upvotes: 3
Reputation: 26039
Just a replace
:
>>> s = 8.5
>>> str(s).replace('.0', '')
8.5
>>> s = 9.0
>>> str(s).replace('.0', '')
9
Cases like 8.05
fail using replace
. To handle such cases, if you want, use re.sub
:
import re
s = 8.05
print(re.sub(r'\.0*$', '', str(s)))
# 8.05
Upvotes: 0