Python – comparing floats and decimals

No matter how old I get, I keep being bitten by the joys of having some data as floats and some as decimals.

ipdb> value
Decimal('1.473')
ipdb> from_value
1.473
ipdb> value < from_value
True

because …

ipdb> from decimal import *
ipdb> Decimal(from_value)
Decimal('1.4730000000000000870414851306122727692127227783203125')

So work out what accuracy you need and do something like

from_value = Decimal(from_value).quantize(Decimal('0.0001'))

One thought on “Python – comparing floats and decimals

Leave a Reply

Your email address will not be published. Required fields are marked *