为什么 float() 会截掉尾随零?

5 python math floating-point numbers decimal

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

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

这是文件的片段

0.96
0.53
0.70
0.53
0.88
0.97
Run Code Online (Sandbox Code Playgroud)

为什么会出现这种情况?有没有办法解决这个问题或者这只是 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
Run Code Online (Sandbox Code Playgroud)

ast*_*yam 6

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

例如:如果输出是 0.96,

x= 0.96
"{0:.4f}".format(x)
Run Code Online (Sandbox Code Playgroud)

输出:

'0.9600'
Run Code Online (Sandbox Code Playgroud)

但输出将是一个字符串..

下面的文章可能值得一读: https ://docs.python.org/2/tutorial/floatingpoint.html

它解释了为什么Python以上述格式显示浮点数。


Ign*_*ams 3

IEEE 754 浮点数(其中floatbinary64)并非旨在保存精度信息。如果您需要这样做,那么您应该使用decimal.Decimal它。

>>> decimal.Decimal('0.70')
Decimal('0.70')
>>> print decimal.Decimal('0.70')
0.70
Run Code Online (Sandbox Code Playgroud)

有关完整详细信息,请参阅decimal文档。