Django Python

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.

[cc lang=”python”]
ipdb> value
Decimal(‘1.473’)
ipdb> from_value
1.473
ipdb> value < from_value True [/cc] because ... [cc lang="python"] ipdb> from decimal import *
ipdb> Decimal(from_value)
Decimal(‘1.4730000000000000870414851306122727692127227783203125’)
[/cc]
So work out what accuracy you need and do something like
[cc lang=”python”]
from_value = Decimal(from_value).quantize(Decimal(‘0.0001’))
[/cc]

Leave a Reply

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