Python Scientific Notation精确标准化

Ale*_*ard 19 python format notation exponential

我的目标是简单地将诸如"1.2"的字符串转换为科学记数法而不增加额外的精度.问题是我总是在输出结束时得到多余的0.

>>> input = "1.2"
>>> print '{:e}'.format(float(input))
1.200000e+00
Run Code Online (Sandbox Code Playgroud)

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

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

>>> print Decimal("1.2000e+4").normalize()
1.2E+4
>>> print Decimal("1.2000e+1").normalize()
12
Run Code Online (Sandbox Code Playgroud)

所以这更好,除了我不想要12,我想要1.2e + 1.:P

任何建议将不胜感激!

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

基本上,我可以输入值"1.23"和"1234.56",它应该是"1.23e + 0"和"1.23456e + 3".

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

orl*_*rlp 35

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

print '{:.2e}'.format(float(input))
Run Code Online (Sandbox Code Playgroud)

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

  • 问题只是我可能不知道该方法中期望的精度是多少。考虑使用此处的方法来识别精度并进行相应调整:http://stackoverflow.com/questions/3018758/define- precision-and-scale-of-pspecial-number-in-python (2认同)

Ale*_*ard 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))
Run Code Online (Sandbox Code Playgroud)

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

  • 您现在可能知道这一点,但格式化语言允许这样:`'{:.{} e}'.format(float(text),get_precision(text)-1)` (4认同)