Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exponent digits in scientific notation in Python

Tags:

In Python, scientific notation always gives me 2 digits in exponent:

print('%17.8E\n' % 0.0665745511651039)
6.65745512E-02

However, I badly want to have 3 digits like:

6.65745512E-002

Can we do this with a built-in configuration/function in Python?

I know my question is basically the same question as: Python - number of digits in exponent, but this question was asked 4 years ago and I don't want to call such a function thousand times. I hope there should be a better solution now.

like image 653
IanHacker Avatar asked Aug 27 '16 19:08

IanHacker


1 Answers

Unfortunately, you can not change this default behavior since you can not override the str methods.

However, you can wrap the float, and use the __format__ method:

class MyNumber:
    def __init__(self, val):
        self.val = val

    def __format__(self,format_spec):
        ss = ('{0:'+format_spec+'}').format(self.val)
        if ( 'E' in ss):
            mantissa, exp = ss.split('E')            
            return mantissa + 'E'+ exp[0] + '0' + exp[1:]
        return ss


     print( '{0:17.8E}'.format( MyNumber(0.0665745511651039)))
like image 75
napuzba Avatar answered Sep 24 '22 16:09

napuzba