简体   繁体   中英

Convert float to integer in Python - invalid literal error

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!

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.

只需写int(float(bidd[0]))

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