3
votes

The float:

fl = 0.000005

casts to String as str(fl)=='5e-06'. however, I want it to cast as str(fl)='0.000005' for exporting to CSV purposes.

How do I achieve this?

2
Do you need to use str() or can you do something like '{:f}'.format(fl)? - grc
as grc has said "{:f}".format(fl) will do what you want - Padraic Cunningham
@PadraicCunningham @grc I get exception Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: zero length field name in format - user2763361
what version of python? Does "{0:f}".format(fl) work? - Padraic Cunningham
Perhaps '{0:.16f}'.format(fl).rstrip('0')? - grc

2 Answers

1
votes

You can just use the standard string formatting option stating the precision you want

>>> fl = 0.000005
>>> print '%.6f' % fl
0.000005
1
votes

Use

fl = 0.00005
s = '%8.5f' % fl
print s, type(s)

Gives

0.00005 <type 'str'>

In case you want no extra digits, use %g (although it uses exponential notation for e.g. 0.000005). See for example:

fl = 0.0005
s = '%g' % fl
print s, type(s)

fl = 0.005
s = '%g' % fl
print s, type(s)

Gives

0.0005 <type 'str'>
0.005 <type 'str'>