I'm parsing some price information from an API, do I need to worry about losing precision if I just do price = float(price_str)?
Or do I have to use decimal.Decimal to make sure the original value is parsed?
Use Decimal class when working with currency! Why? Let's see this dummy example:
float('0.2') + float('0.1')
Result: 0.30000000000000004
With Decimal instead:
Decimal('0.2') + Decimal('0.1')
Result: Decimal('0.3')
UPDATE:
if you are using third party API with json format, you can use Decimal to automatically parse floating numbers automatically: see my blog post: http://www.daveoncode.com/2014/10/21/python-reading-numbers-from-json-without-loss-of-precision-using-decimal-class-for-data-processing/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With