acdr acdr - 1 month ago 5
Python Question

String formatting of floats

I would like to convert a number to a string in such a way that it only shows a certain number of significant digits, without superfluous zeros. The following is an example of some desired in/outputs, given that I want 5 significant digits:

0.0000123456789 > 1.2346e-5
0.00123456789 > 1.2346e-3
0.123456789 > 1.2346e-1
1.23456789 > 1.2346
1234.56789 > 1234.6
1234567.89 > 1.2346e6


The
g
option of string formatting (https://docs.python.org/2/library/string.html#format-specification-mini-language) comes pretty close, but its behaviour isn't quite what I'm looking for for numbers smaller than 1, but not much smaller than 1:

"{:.5g}".format(0.000123456789) # returns '0.00012346', I want '1.2346e-4'


Is it possible to manipulate the behaviour of one of the existing formatters to do this?

Answer
'{:.4g}'.format(float(input)) if x<=1000 or x>=.0001 else '{:.4e}'.format(float(input))
Comments