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/
price_strlook like?float()can only parse up to 17 numbersdecimal.Decimal. why do you not want to?floatcan have as many digits as you like, and they're all taken into account when determining which way to round. Compare the results offloat('8000000000000000.5')andfloat('8000000000000000.500000000001'), for example.