Reputation: 5134
I understand that I can convert a number in scientific notation to a float with float
like this:
>>> x = 1.3e8
>>> float(x)
130000000.0
Then, why can I not do the same thing with a negative exponent?
>>> x = 1.3e-8
>>> x
1.3e-08
>>> float(x)
1.3e-08
I would have expected for float(x)
in the last case to give 0.000000013
Upvotes: 1
Views: 3886
Reputation: 684
The following function deals with an arbitrary number of floating points.
def displayfloat(x):
# format numbers > 1.
if str(x).find('+') > -1:
return '{:.1f}'.format(x)
e_idx = str(x).find('e')
# format numbers > 1e-05
if e_idx == -1:
return str(x)
# format numbers < 1e-05
minus_idx = str(x).find('-')
shift = e_idx
if str(x).find('.') > -1:
shift -= 1
decimalpoints = -int(str(x)[str(x).find('-'):]) - 1 + shift
floatformat = '{:.'+str(decimalpoints)+'f}'
return floatformat.format(x)
# exmaples
displayfloat(1e-5) # --> '0.00001'
displayfloat(1.1e-5) # --> '0.000011'
displayfloat(1e+5) # --> '100000.0'
Upvotes: 0
Reputation: 149806
1.3e-8
is a floating point literal (i.e. it directly creates a float
object) so you don't need to wrap it in a float()
. The Python shell simply returns the default string representation of a float. To force the fixed-point notation, you can use str.format()
, although you may need to specify the precision:
>>> '{:.9f}'.format(1.3e-8)
'0.000000013'
Upvotes: 1
Reputation: 1440
It is already a float, it just stays represented in scientific notation
print(type(1.3e8)) # <class 'float'>
print(type(1.3e-8)) # <class 'float'>
print(0.000000013) # 1.3e-08
Upvotes: 0