简体   繁体   English

Python Scientific Notation精确标准化

[英]Python Scientific Notation precision normalizing

My goal is simply to convert a string such as "1.2" to scientific notation without adding additional precision. 我的目标是简单地将诸如“1.2”的字符串转换为科学记数法而不增加额外的精度。 The problem is that I always end up with superfluous 0s at the end of my output. 问题是我总是在输出结束时得到多余的0。

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

I'm trying to figure out how to get just 1.2e+00 . 我想弄清楚如何得到1.2e+00 I realize I can specify precision in my format statement, but I don't want to truncate longer strings unnecessarily. 我意识到我可以在我的格式语句中指定精度,但我不想不必要地截断更长的字符串。 I just want to suppress the training 0s. 我只是想压制训练0。

I've tried using Decimal.normalize(), which works in all cases, except where e < 2. 我尝试过使用Decimal.normalize(),它适用于所有情况,除了e <2。

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

So that's better, except I don't want 12, I want 1.2e+1. 所以这更好,除了我不想要12,我想要1.2e + 1。 :P :P

Any suggestions would be greatly appreciated! 任何建议将不胜感激!

Edit: To clarify, the input value has already been rounded appropriately to a predetermined length that is now unknown. 编辑:为了澄清,输入值已经适当地舍入到预定长度,现在是未知的。 I'm trying to avoid recalculating the appropriate formatting precision. 我试图避免重新计算适当的格式精度。

Basically, I could have input values of "1.23" and "1234.56", which should come out as "1.23e+0" and "1.23456e+3". 基本上,我可以输入值“1.23”和“1234.56”,它应该是“1.23e + 0”和“1.23456e + 3”。

I may have to just check how long the input string is and use that to specify a precision manually, but I wanted to check and make sure I just wasn't missing something that could just prevent the exponential format from arbitrarily adding 0s. 我可能只需要检查输入字符串的长度并使用它来手动指定精度,但我想检查并确保我没有遗漏可能阻止指数格式任意添加0的东西。

You can specify precision in the format: 您可以使用以下格式指定精度:

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

This will always give 2 decimals of precision. 这将始终给出2位小数的精度。 The amount of precision you want must be determined by yourself. 您想要的精确度必须由您自己决定。 If you need any help with that post in the comments. 如果您在评论中需要该帖子的任何帮助。

Just going back through and cleaning up old questions. 回过头来清理旧问题。 I ended up solving this by writing a little function to intuit the initial precision of a number and then using it to format the output result. 我最后通过编写一个小函数来解决这个问题,以便直观地计算数字的初始精度,然后用它来格式化输出结果。

#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))

Not really the most elegant solution, but the task was kind of obnoxious to begin with and it got the job done. 这不是最优雅的解决方案,但是任务开始时有点令人讨厌,并且完成了工作。

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. 它花了一些调整Alex的解决方案,但我编写了一个函数,可以删除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]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM