Reputation: 9542
What is the best way to control printing of 64-bit floating point numbers in Python?
I can use the %e
specifier to easily show all numbers in exponential format. However, I only want to use exponential format if the number has more than x amount of digits in it. For example, below is the raw 64-bit floating point number and what I would like it to look like as a string:
value what's printed
1.123456 1.123456
123456.1234 12345.6e4
1.0 1.0
.1234567 1.23456e-1
Above I only want to see 7 digits total and then convert to exponential notation if there are more needed.
Does this make any sense? Essentially I would like to be able to use exponential notation only when some threshold for the number is reached. I know %e
allows specifiers like %.3e
but this will always use exponential notation regardless of the number size.
Upvotes: 1
Views: 2897
Reputation: 9542
I suppose I could do something like:
>>> def pretty_float(val):
... if len(repr(val)) > 7:
... return '%e' % val
... else:
... return repr(val)
...
Upvotes: 1
Reputation: 309939
You can probably cook up something with '%g'
-- which will use the shorter of %f
or %e
:
>>> '%.4g'%(1154.2)
'1154'
>>> '%.4g'%(11545.2)
'1.155e+04'
>>> '%.4g'%(1.15452)
'1.155'
>>> '%.4g'%(0.000005321)
'5.321e-06'
In other words, this will print out a number with 4 significant digits and use scientific notation where necessary.
Upvotes: 1