Python Scientific Notation precision normalizing Python Scientific Notation precision normalizing python python

Python Scientific Notation precision normalizing


You can specify precision in the format:

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

This will always give 2 decimals of precision. 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 stringdef 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 textclass 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.

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'+evals = 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]))