打印不带 DECIMAL 字且不带浮点数转换的十进制数

Print decimal numbers without DECIMAL word and without float conversion

我执行了一个简单的归一化过程:

a = range(5)
norm = [Decimal(i)/sum(a) for i in a]
print norm

输出:

[Decimal('0'), Decimal('0.1'), Decimal('0.2'), Decimal('0.3'), Decimal('0.4')]

但我只想打印:

[0, 0.1, 0.2, 0.3, 0.4]

我该如何纠正这个问题?请帮忙。

PS:这只是我试过的一个例子。我的实际数据有巨大的浮点数。我想这样做以避免浮点错误。我希望结果是小数而不是浮点数。

使用 print(str(Decimal)) 代替 print(Decimal) :

print [str(i) for i in norm]
['0', '0.1', '0.2', '0.3', '0.4']

为了 print Decimals 而没有 'Decimal' 出现,你可以继承 Decimal 并覆盖 __repr__:

>>> class MyDecimal(Decimal):
...   def __repr__(self):
...     return str(float(self))
...
>>> x = Decimal(4.1)
>>> x
Decimal('4.0999999999999996447286321199499070644378662109375')
>>> y = MyDecimal(5.3)
>>> y
5.3

但是,当您对它们进行任何操作时,repr 会恢复到原来的形式:

>>> y = MyDecimal(5.3)
>>> z = MyDecimal(4.2)
>>> y + z
Decimal('9.500000000000000000000000000')

在这种情况下要始终获得 MyDecimal,您需要将 Decimal 的所有操作覆盖到 return 一个 MyDecimal 对象而不是 Decimal.

请注意,我们在这里看到的是小数的表示形式。在进行其他操作时,您需要保持原样。或者在别处使用时总是转换为浮点数。 From the docs:

Decimal objects cannot generally be combined with floats in arithmetic operations: an attempt to add a Decimal to a float, for example, will raise a TypeError. There’s one exception to this rule: it’s possible to use Python’s comparison operators to compare a float instance x with a Decimal instance y. Without this exception, comparisons between Decimal and float instances would follow the general rules for comparing objects of different types described in the Expressions section of the reference manual, leading to confusing results.