Skip to content Skip to sidebar Skip to footer

Exponent Digits In Scientific Notation In Python

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

Solution 1:

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

Solution 2:

You can use your own formatter and override format_field:

import string
class MyFormatter(string.Formatter): 
    def format_field(self, value, format_spec):
        ss = string.Formatter.format_field(self,value,format_spec)
        if format_spec.endswith('E'):
            if ( 'E'in ss):
                mantissa, exp = ss.split('E')
                return mantissa + 'E'+ exp[0] + '0' + exp[1:]                  
        return ss

print( MyFormatter().format('{0:17.8E}',0.00665745511651039) )

Post a Comment for "Exponent Digits In Scientific Notation In Python"