Comparing Floats in Python unit tests


Comparing Floats in Python unit tests

2017/06/03

Tags: python unit tests almostEqual

When you are comparing floats in an unit test, a common notion is to round off the numbers being compared to some places.

self.assertEquals(obj.change(), round(decimal.Decimal(0.471404524888533), 8))

You could rewrite this as:

self.assertAlmostEqual(obj.change(), 0.471404524888533, places=8)

This will round off both obj.change()’s value and 0.471404524888533 to 8 decimal places and then compare.