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.
Simply write int(float(bidd[0]))
Related
I have a function which takes a string input, tries to convert it to integer and then proceeds with two alternative paths depending on whether the conversion succeeded or not:
def make_int(arg):
try:
int_value = int(arg)
except ValueError:
str_value = arg
I now was quite surprised when the string '123_2307_7' was happily converted to the integer 12323077 - whereas I was expecting it to follow the str path here. What details of str -> int conversion is it I have not yet grokked?
As pointed out by #jonrsharpe the docs says you can embed single _ charcaters in your integer literal - which are simply ignored. Closing.
In python you can write any integer/float this way :
XXX_XXX_XXX
Keep in mind that integer/float are objects in python.
I am a newbie to programming and I recently came across this error. I am working on the Space Analysis dataset from Kaggle and the Price column is a panda series. I tried using astype() to convert it into float and int which was working fine a while ago but now it shows me the Value error. When the astype() is removed the TypeError: '<' not supported between instances of 'str' and 'int' occurs.
df_money = df_.groupby(["Organisation"])["Price"].sum().reset_index()
df_money["Price"] = df_money["Price"].astype('float')
df_money = df_money[df_money["Price"]>0]
df_money.head()
Error was:
ValueError: invalid literal for int() with base 10: '48.5200.048.5200.0200.0200.037.0200.037.0200.0200.037.0200.0200.037.0200.0200.037.0200.037.0200.0200.0200.037.0200.0200.037.0200.037.0200.0200.0200.0200.037.0200.0200.0200.0200.037.0200.0200.037.0200
This means some record in your Price column likely has a string with the literal value "48.5200.048.5200.0200.0200.037.0200.037.0200.0200.037.0200.0200.037.0200.0200.037.0200.037.0200.0200.0200.037.0200.0200.037.0200.037.0200.0200.0200.0200.037.0200.0200.0200.0200.037.0200.0200.037.0200"
This string format cannot be naively converted to a number, and thus the conversion fails.
Later you do a comparison between that column and > 0. Python, while dynamic, is still strongly typed, meaning that you can only usually compare values of the same type. A string isn't a number and cannot be compared to a number, hence the TypeError if the Pricing column contains strings.
To resolve your issue, you will have to somehow convert your long string to something that can be converted to a number. You can typically only convert something with a single decimal separator. For example, float("48.5200") will work, but float("48.5200.048") won't.
I believe your groupby.sum() is probably creating this long string. Convert the Price column to a float before doing the groupby operation.
have strange problem to cant know it . I will be thankful to help me .......enter image description here
You've to enter integers to convert it to int. You cannot convert "hi" to integer for example. What will be the value of int("hi")? For sure it'll give error. Try adding integers as input. If you're confused, take input in integer format only by writing varodi=int(input(":")) and take 1 as input to break the loop. Change the statement to if varodi==1: then break. Or else just put the input as integer
I am having a slight issue with math's .isnan() function in python. Pretty much, I have this code:
import math
diceChoice = raw_input('Which dice will you throw?\n 4 sides\n 6 sides\n 12 sides?\n>')
if math.isnan(float(diceChoice)):
print(str(diceChoice) + ' is an invalid choice')
and if diceChoice isn't a number (eg 'a') it gives me the error:
ValueError: could not convert string to float: a
If I don't convert it to a float, it gives me another error saying that it needs to be a float. I must be doing something wrong as the isnan function would be useless if it only accepts numbers. Can someone please help me
Thanks in advance
The float() function used on any other string other than a decimal number, 'nan', '-inf' or 'inf' (or slight variants of those strings) will throw a ValueError instead, because anything else is not a valid floating point value. math.isnan() only works on the special float value float('nan'), but it is not ever called if float() raises an exception first.
Use exception handling to catch that error instead:
try:
diceChoice = int(diceChoice))
except ValueError:
print(diceChoice, 'is an invalid choice')
I used int() instead because your input requires that the user enters a whole number.
Just to be explicit: float('nan') is a specific floating point value to signify the output of certain mathematical operations that are not an exception. It is never used to signify invalid input.
isnan() is really only used to check if a number doesn't have a finite value. Consider instead doing something like:
if not diceChoice.isdigit():
The error is raised because you attempt to convert a string to an integer with float('a'). Easier to just do the above.
NaN are used to define things that are not numbers in a floating point context like 0/0 or the square root of a negative number for example. You can use isdigit or something else.
Python provides a convenient method long() to convert string to long:
long('234')
; converts '234' into a long
If user keys in 234.89 then python will raise an error message:
ValueError: invalid literal for long()
with base 10: '234.89'
How should we a python programmer handles scenarios where a string with a decimal value ?
Thank you =)
longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.
So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int
Well, longs can't hold anything but integers.
One option is to use a float: float('234.89')
The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))
>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L