简体   繁体   中英

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?

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/

Prices should be decimal, floats often introduce rounding errors which will give you headaches in the long run. Example:

In [1]: 3*0.1
Out[1]: 0.30000000000000004

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM