繁体   English   中英

为什么 float() 会切断尾随零?

[英]Why does float() cut off trailing zeros?

该代码成功地将一个包含许多数字的大文件裁剪为几个带有数字的较小文本文件,但它产生了一个有趣的怪癖。

所有数字都应该是小数点后四位,例如 2.7400,但它们打印为 2.74。

这是一个文件的片段

0.96
0.53
0.70
0.53
0.88
0.97

为什么会这样? 有没有办法解决这个问题,或者这只是 float() 的一个怪癖?

from itertools import islice

def number_difference(iterable):
    return float(iterable[-1].strip('\n')) - float(iterable[0].strip('\n'))

def file_crop(big_fname, chunk_fname, no_lines):
    with open(big_fname, 'r') as big_file:
        big_file.readline()
        ifile = 0
        while True:
            data = list(islice(big_file, no_lines))
            if not data:
                break
            with open('{}_{}.locs'.format(chunk_fname, ifile), 'w') as small_file:
                offset = int(float(data[0].strip('\n')))
    map(lambda x: str(float(x.strip('\n')) - offset) + '\n', data)
    small_file.write('{} {} L\n'.format(len(data), number_difference(data)))
        small_file.write(''.join(map(lambda x: str(round((float(x.strip('\n')) - offset),4)) + '\n', data)))
            ifile += 1

您可以通过格式化输出来保留零:

例如:如果输出为 0.96,

x= 0.96
"{0:.4f}".format(x)

浮点数只是python(和其他编程语言)中的近似值......例如,小数被计算为二进制值。 很难找到大多数以 10 为底的操作的确切值

仔细查看此链接后,您会明白为什么 python 没有为您的以 2 为基数转换的操作提供准确的值

https://docs.python.org/2/tutorial/floatingpoint.html

使用 print 也可以完成这项工作

print("%.4f" % 0.96) or
whatever_file.write("%.4f" % 0.96)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM