0

How do I convert this number to an integer I can do simple math with?! (eg. 10.5200 below.)

{"bid":["10.52000000","0.70824000"],"ask":["10.54000000","2.07336000"],"seq":2456916}

I get the following error, and it's driving me mental:

ValueError: invalid literal for int() with base 10: '10.52'

This is what I'm running:

bitfl = json.loads(bitfl)
bid = bitfl['bid']
ask = bitfl['ask']
bidd = bid[0] #edit - this is actually in, as it's a list
askk = ask[0]
print('diff: %i' % (int(bidd[0]) - int(askk[0])))

I don't know WHY it should be so difficult to just accept "10.52" as a string or float or unicode and just convert it to a normal, calculable integer!

Any help MUCH appreciated!

1
  • 2
    10.52 is obviously not a valid integer. Convert to float and then to int. Commented Aug 25, 2012 at 2:20

2 Answers 2

4

The problem is that you are trying to convert a string containing a non-integer to an integer.

The easiest/best solution is using int(float(yourstring))

Since you receive the data as JSON you should also consider requiring whatever client is providing the data not to use strings for non-string data.

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

2 Comments

@KnutOle: What about them? If you want an integer you need to get rid of the decimals, since integers are whole numbers.
You still get ValueError: could not convert string to float: - Am I missing something?
1

Simply write int(float(bidd[0]))

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.