Python字符串到十进制转换 - 奇怪的结果

时间:2015-01-22 00:39:14

标签: python-2.7 decimal

我在python中使用Decimal模块,并在转换字符串时看到一些相当奇怪的行为。

print "orig = %s dec = %.19f" % (rate,Decimal(rate))

结果:

orig = 0.0151 dec = 0.0151000000000000006
orig = 0.00995 dec = 0.0099500000000000005
orig = 0.011075 dec = 0.0110749999999999998
orig = 0.0123 dec = 0.0123000000000000002
orig = 0.01 dec = 0.0100000000000000002
orig = 0.047025 dec = 0.0470249999999999974

或许甚至更多关于舍入小数似乎也会产生奇怪的结果

print "orig = %.19f rep = %.19f" % (originalCashflow,replacementCashflow)
originalCashflow = originalCashflow.quantize(Decimal('1.00'), rounding=ROUND_HALF_UP)
replacementCashflow = replacementCashflow.quantize(Decimal('1.00'), rounding=ROUND_HALF_UP)
print "orig = %.19f rep = %.19f" % (originalCashflow,replacementCashflow)

结果:

orig = -10028392.3750000000000000000 rep = -10028392.3750000000000000000
orig = -10028392.3800000008195638657 rep = -10028392.3699999991804361343

这似乎不对。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您没有转换字符串。你正在转换花车。

orig = 0.0151
orig_str = "0.0151"

decimal.Decimal(orig)

输出:

Decimal('0.01510000000000000057454041524351850966922938823699951171875')

字符串转换是准确的。

decimal.Decimal(orig_str)

输出:

Decimal('0.0151')

Floats are not exact.