在Python中将输出格式化为固定精度

在Python中将输出格式化为固定精度,python,Python,我希望昏迷后总是有5个数字 例如: 我的数据是105.565 105。165.54 我想要同样的长度:105.56565 105.00000165.54000 脚本: from pylab import* from rtlsdr import* from bluetooth import* import sys #configure device sdr= RtlSdr() sdr.sample_rate=double(sys.argv[3]) sdr.gain=double(sys.argv

我希望昏迷后总是有5个数字

例如: 我的数据是105.565 105。165.54

我想要同样的长度:105.56565 105.00000165.54000

脚本:

from pylab import*
from rtlsdr import*
from bluetooth import*
import sys

#configure device
sdr= RtlSdr()
sdr.sample_rate=double(sys.argv[3])
sdr.gain=double(sys.argv[2])
sdr.center_freq=double(sys.argv[1])

#Bluetooth connection

server_sock=BluetoothSocket(RFCOMM)
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port=server_sock.getsockname()[1]
uuid="94f39d29-7d6d-437d-973b-fba39e49d4ee"
client_sock,client_info=server_sock.accept()

while(1):
        samples=sdr.read_samples(256*1024)
        result=psd(samples,NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=sdr.center_freq*1e6/1e6)
        freq=result[1]/1e6
        value_freq=str(freq)[1:-1]
        print format(freq, '%5f') // he do not work

在最后一句话中,我想你应该:

print "%5f" % freq

希望这有帮助

实现你想要的有点粗糙的方法:

n = 105.5656534567
n = float(str(n)[0:9])

print(n)
给出:

105.56565

format
内置(和
str.format
)使用的格式语言与
%
运算符使用的
printf
样式格式不完全相同。您应该了解有关语言的详细信息


对于您的具体情况,我怀疑您需要
格式(freq,.5f)
。这将始终在小数点后给出您的五位数字。

我这样做了:
tab\u freq=(result[]/1e6)tab\u freq\u convert=str(tab\u freq)[1:-1]value\u freq=format(tab\u freq\u convert,.5f”)
但我总是有相同的错误:
对于'str类型的对象,未知的格式代码'f',不将其四舍五入到所需的小数位数。用
n=105.5656599999试试