Python Scientific Notation精确标准化

时间:2011-04-06 20:38:54

标签: python format notation exponential

我的目标只是将字符串(如“1.2”)转换为科学记数法而不添加额外的精度。问题是我总是在输出结束时得到多余的0。

>>> input = "1.2"
>>> print '{:e}'.format(float(input))
1.200000e+00

我正在试图找出如何获得1.2e+00。我意识到我可以在我的格式语句中指定精度,但我不想不必要地截断更长的字符串。我只想抑制训练0。

我尝试过使用Decimal.normalize(),它适用于所有情况,除非e< 2。

>>> print Decimal("1.2000e+4").normalize()
1.2E+4
>>> print Decimal("1.2000e+1").normalize()
12

这样更好,除了我不想要12,我想要1.2e + 1。 :P

任何建议都将不胜感激!

修改 为了澄清,输入值已经适当地舍入到预定长度,现在是未知的。我试图避免重新计算适当的格式精度。

基本上,我的输入值可以是“1.23”和“1234.56”,应该是“1.23e + 0”和“1.23456e + 3”。

我可能只需检查输入字符串的长度并使用它来手动指定精度,但我想检查并确保我没有遗漏可能阻止指数格式任意添加0的东西

3 个答案:

答案 0 :(得分:35)

您可以采用以下格式指定精度:

print '{:.2e}'.format(float(input))

这将始终给出2位小数的精度。您想要的精确度必须由您自己决定。如果您在评论中需要任何关于该帖子的帮助。

答案 1 :(得分:7)

回过头来清理旧问题。我最后通过编写一个小函数来解决这个问题,直观地计算数字的初始精度,然后用它来格式化输出结果。

#used to determine number of precise digits in a string
def get_precision(str_value):
    vals =  str_value.split('.')
    if (vals[0] == '0'):
        return len(vals[1])
    else:
        return len(str_value) -1

# maintain same precision of incoming string on output text
class ExpDecorator(CurrencyDecorator):
    def get_text(self):
        text = self.decoratedCurrency.get_text()
        return ('{:.' + str(get_precision(text)-1) + 'e}').format(float(text))

这不是最优雅的解决方案,但这项任务有点令人讨厌,并且完成了工作。

答案 2 :(得分:0)

It took a bit of tweaking Alex's solution but I wrote a function that would remove all trailing zeros from any number in python.

def remove_trailing_zeros(value):
value = str(value)
if value.find('e') != -1:
    vals = value.split('e')
    e = vals[1]
    return '{:g}'.format(float(vals[0]))+'e'+e
vals = value.split('.')
if (vals[0] == '0'):
    i = 0
    while vals[1][i] == '0':
        i += 1
    return '{:.{}e}'.format(float(value), len(vals[1][i:]) - 1)
else:
    j = len(vals[0]) - 1
    while vals[0][j] == '0':
        j -= 1
    return '{:.{}e}'.format(float(value), len(vals[0][:j]))
相关问题