Number of digits in exponent

后端 未结 4 1731
忘了有多久
忘了有多久 2020-12-01 14:30

Is it possible to set the number of digits to be used for printing the exponent of a floating-point number? I want to set it to 3.

Currently,

f = 0.0         


        
4条回答
  •  生来不讨喜
    2020-12-01 14:38

    Similar to @Anurag Uniyal answer, but optionally removing the sign in the exponent (useful if one is tight in space).

    def expformat(f, prec, exp_digits, sign='on'):
        """Scientific-format a number with a given number of digits in the exponent.
        Optionally remove the sign in the exponent"""
        s = "%.*e"%(prec, f)
        mantissa, exp = s.split('e')
        if (sign=='on') :
            # add 1 to digits as 1 is taken by sign +/-
            return "%se%+0*d"%(mantissa, exp_digits+1, int(exp))
        else :
            return "%se%0*d"%(mantissa, exp_digits, int(exp))
    

提交回复
热议问题