Chironex
Chironex

Reputation: 413

Python: Suppress exponential format (i.e. 9e-10) in float to string conversion?

I want to use python to write code for another language which doesn't understand exponentially formatted floats. Is there an easy way to get python to, when converting floats to strings, use long-form notation (I.E. 0.000000009 instead of 9e-9)? I tried '%(foo)f', but it cuts the decimal short (0.00000).

Upvotes: 1

Views: 5689

Answers (2)

Claudiu
Claudiu

Reputation: 229361

Use a specific format specifier, e.g.:

>>> f=9*(10**-9)
>>> str(f)
'9e-09'
>>> "%.23f" % f
'0.00000000900000000000000'

UPDATE (thanks to @Sven): The amount of digits you want to use depends on the magnitude of the number. if you have large numbers (like several trillions) you won't need any decimals, obviously. for tiny numbers you need more. 'tis an ugly representation indeed.

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601599

Try something like

"%.16f" % f

This will still use exponential format if the number is too small, so you have to treat this case separately, for example

"%.16f" % f if f >= 1e-16 else "0.0"

Upvotes: 2

Related Questions