如何获得python的小数精度?
问题描述:
这里的情况是:如何获得python的小数精度?
- 我写一个单元测试,通过对比这是
PostgreSQL
NUMERIC
精确的货币(10, 2)
我test
已经宣称为
self.assertEquals(Decimal(89.12), user_two_transactions[0].amount)
我获得失败为
AssertionError: Decimal('89.1200000000000045474735088646411895751953125') != Decimal('89.12')
我怎样才能让它更精确,并确保金额正确保存在数据库中?
答
初始化十进制用字符串:
Decimal('89.12')
正如你可以看到,89.12不能准确地为float来表示。
Decimal construction documentation.
你的另一种选择是一个(sign, digits, exponent)
元组:
In [3]: Decimal((0, (8, 9, 1, 2), -2))
Out[3]: Decimal('89.12')
但请不要做,没有一个很好的理由:)
巨大的感谢!我错过了 – daydreamer