2

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?

5
  • Can you show that what's price_str look like? Commented Jul 7, 2015 at 9:09
  • How long is the string? float() can only parse up to 17 numbers Commented Jul 7, 2015 at 9:09
  • i would have used decimal.Decimal. why do you not want to? Commented Jul 7, 2015 at 9:10
  • @TimCastelijns: I'm not sure what you mean. The input to float can have as many digits as you like, and they're all taken into account when determining which way to round. Compare the results of float('8000000000000000.5') and float('8000000000000000.500000000001'), for example. Commented Jul 7, 2015 at 9:40
  • @satoru read my update about json and Decimal class ;) Commented Jul 7, 2015 at 10:14

2 Answers 2

6

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/

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.