Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

python - Number of digits in exponent

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.0000870927939438012
>>> "%.14e"%f
'8.70927939438012e-05'
>>> "%0.14e"%f
'8.709279e-005'

What I want to print is: '8.70927939438012e-005'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a no way to control that, best way is to write a function for this e.g.

def eformat(f, prec, exp_digits):
    s = "%.*e"%(prec, f)
    mantissa, exp = s.split('e')
    # add 1 to digits as 1 is taken by sign +/-
    return "%se%+0*d"%(mantissa, exp_digits+1, int(exp))

print eformat(0.0000870927939438012, 14, 3)
print eformat(1.0000870927939438012e5, 14, 3)
print eformat(1.1e123, 4, 4)
print eformat(1.1e-123, 4, 4)

Output:

8.70927939438012e-005
1.00008709279394e+005
1.1000e+0123
1.1000e-0123

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...