首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >指数中的位数

指数中的位数
EN

Stack Overflow用户
提问于 2012-03-28 23:37:30
回答 4查看 20.3K关注 0票数 24

是否可以设置用于打印浮点数指数的位数?我想将其设置为3。

目前,

代码语言:javascript
复制
f = 0.0000870927939438012
>>> "%.14e"%f
'8.70927939438012e-05'
>>> "%0.14e"%f
'8.709279e-005'

我想打印的是:'8.70927939438012e-005'

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-03-29 00:22:07

没有办法控制这一点,最好的方法是为此编写一个函数,例如

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
8.70927939438012e-005
1.00008709279394e+005
1.1000e+0123
1.1000e-0123
票数 22
EN

Stack Overflow用户

发布于 2018-11-14 19:35:13

您可以使用np.format_float_scientific

代码语言:javascript
复制
from numpy import format_float_scientific

f = 0.0000870927939438012

format_float_scientific(f, exp_digits=3) # prints '8.70927939438012e-005'

format_float_scientific(f, exp_digits=5, precision=2) #prints '8.71e-00005'
票数 17
EN

Stack Overflow用户

发布于 2018-10-10 09:26:29

这里有一个稍微更灵活的答案( 'e''E'来分离尾数和指数,是宽恕缺失/错误的参数)。但我推荐@AnuragUniyal的答案,因为这个答案太简洁了。

代码语言:javascript
复制
def efmte(x, n=6, m=2, e='e', nmax=16):
    def _expc(s): # return exponent character of e-formatted float
        return next(filter(lambda character: character in {'E', 'e'}, s))
    def _pad0(s, n): # return string padded to length n
        return ('{0:0>' + str(n) + '}').format(s)
    def _efmtes(s, n): # reformat e-formatted float: n e-digits
        m, e, p = s.partition(_expc(s)) # mantissa, exponent, +/-power
        return m + e + p[0] + _pad0(p[1:], n)
    def _efmt(x, n, e): # returns formatted float x: n decimals, 'e'/'E'
        return ('{0:.' + str(n) + e + '}').format(x)
    x = x if isinstance(x, float) else float('nan')
    nmax = 16 if not isinstance(nmax, int) else max(0, nmax)
    n = 6 if not isinstance(n, int) else min(max(0, n), nmax)
    m = 2 if not isinstance(m, int) else max(0, m)
    e = 'e' if e not in {'E', 'e'} else e
    return _efmtes(_efmt(x, n, e), m)

示例:

代码语言:javascript
复制
>>> efmte(42., n=1, m=5)
'4.2e+00001'
>>> efmte('a')
'-1.#IND00e+00'
>>> # Yuck: I was expecting 'nan'. Anyone else?
>>> from math import pi
>>> efmte(pi)
'3.141593e+00'
>>> efmte(pi, m=3)
'3.141593e+000'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9910972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档