【发布时间】:2016-12-07 06:48:14
【问题描述】:
我有一系列浮点数,需要以特定格式打印出来,与科学记数法非常相似。 给定数字-345.678,科学计数法会给我-3.45678E2,但我需要输出-.345678D03。具体来说,小数点左边不能有任何数字。有没有办法在 Python 3 中做到这一点?
【问题讨论】:
标签: floating-point python-3.5 number-formatting scientific-notation
我有一系列浮点数,需要以特定格式打印出来,与科学记数法非常相似。 给定数字-345.678,科学计数法会给我-3.45678E2,但我需要输出-.345678D03。具体来说,小数点左边不能有任何数字。有没有办法在 Python 3 中做到这一点?
【问题讨论】:
标签: floating-point python-3.5 number-formatting scientific-notation
我不确定您的格式的全部细节,但以下内容应该可以工作或可以轻松修改以工作:
from decimal import Decimal
def sci_str(dec):
return ('{:.' + str(len(dec.normalize().as_tuple().digits) - 1) + 'E}').format(dec)
def mod_sci_str(x):
s = sci_str(10*Decimal(str(x)))
s = s.replace('E+','D0')
s = s.replace('E-','D0-')
s = s.replace('.','')
if s.startswith('-'):
return '-.' + s[1:]
else:
return '.' + s
sci_str 函数是一个聪明的实用程序,因为 @MikeM 在这个问题中
例如:
>>> mod_sci_str(-345.678)
'-.345678D03'
>>> mod_sci_str(345.678)
'.345678D03'
>>> mod_sci_str(0.0034)
'.34D0-2'
【讨论】: