1

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.

4

2 回答 2

1

您可能可以用'%g'-- 来做一些事情,这将使用 or 的较短%f%e

>>> '%.4g'%(1154.2)
'1154'
>>> '%.4g'%(11545.2)
'1.155e+04'
>>> '%.4g'%(1.15452)
'1.155'
>>> '%.4g'%(0.000005321)
'5.321e-06'

换句话说,这将打印出一个具有 4 位有效数字的数字,并在必要时使用科学计数法。

于 2012-10-31T18:44:39.430 回答
1

我想我可以做类似的事情:

>>> def pretty_float(val):
...   if len(repr(val)) > 7:
...     return '%e' % val
...   else:
...     return repr(val)
... 
于 2012-10-31T18:52:55.557 回答