在Python中将小数位数打印到8位精度?

时间:2018-07-28 15:38:26

标签: python python-3.x

下面的代码打印各种精度的小数,但恢复到7位后的科学计数法。我需要在用户界面中显示至少8个位置的字符串宽度。

如何获取8位精度的字符串化小数?

from decimal import *
getcontext().prec = 8 # set precision to 8 decimal points. 
getcontext().rounding = "ROUND_DOWN" # alway round down 

# stringified zero of various precisions

zw = ['0', '0.0', '0.00', '0.000000', '.00000000', '0.00000000', '0.000000000000']

for n in range(0,len(zw)): 
    zstr = zw[n]                # stringified zero 
    zdec = Decimal(zstr)        # decimalized zero
    print (zstr, ":", zdec) # compare stringified and decimalized zero

2 个答案:

答案 0 :(得分:1)

使用format / f和字符串格式(docs):

for zstr in zw:   
    zdec = Decimal(zstr)
    print (zstr, ":", f'{zdec:.8f}') 

0 : 0.00000000
0.0 : 0.00000000
0.00 : 0.00000000
0.000000 : 0.00000000
.00000000 : 0.00000000
0.00000000 : 0.00000000
0.000000000000 : 0.00000000

答案 1 :(得分:1)

尝试:

from decimal import *
getcontext().prec = 8 # set precision to 8 decimal points. 
getcontext().rounding = "ROUND_DOWN" # alway round down 

# stringified zero of various precisions

zw = ['0', '0.0', '0.00', '0.000000', '.00000000', '0.00000000', '0.000000000000']

for zstr in zw: 
    zdec = Decimal(zstr)        # decimalized zero
    print ('{} : {:.8f}'.format(zstr, zdec)) # compare stringified and decimalized zero

打印:

0 : 0.00000000
0.0 : 0.00000000
0.00 : 0.00000000
0.000000 : 0.00000000
.00000000 : 0.00000000
0.00000000 : 0.00000000
0.000000000000 : 0.00000000