Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get decimal precision in python?

Here is the situation:

  • I am writing a unit test and comparing the currency which is NUMERIC in PostgreSQL with precision (10, 2)

My test has assert as

self.assertEquals(Decimal(89.12), user_two_transactions[0].amount)

I get failure as

AssertionError: Decimal('89.1200000000000045474735088646411895751953125') != Decimal('89.12')

How can I make it more precise and be sure that the amount is saved correctly in database?

like image 768
daydreamer Avatar asked Aug 31 '25 03:08

daydreamer


1 Answers

Initialize the Decimal with a string:

Decimal('89.12')

As you can see, 89.12 cannot be represented exactly as a float.

Decimal construction documentation.

Your other option is a (sign, digits, exponent) tuple:

In [3]: Decimal((0, (8, 9, 1, 2), -2))
Out[3]: Decimal('89.12')

but please don't do that without a good reason :)

like image 173
Pavel Anossov Avatar answered Sep 02 '25 15:09

Pavel Anossov