Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I convert any string to float without losing precision in Python?

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?

like image 578
satoru Avatar asked Jul 14 '26 21:07

satoru


1 Answers

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/

like image 84
daveoncode Avatar answered Jul 16 '26 11:07

daveoncode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!