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 =)
By converting a string into long we are translating the value of string type to long type. In Python3 int is upgraded to long by default which means that all the integers are long in Python3. So we can use int() to convert a string to long in Python.
In Python 2.7. there are two separate types “int” (which is 32 bit) and “long int” that is same as “int” of Python 3.x, i.e., can store arbitrarily large numbers.
Strings can be converted to integers by using the int() method. If your string does not have decimal places, you'll most likely want to convert it to an integer by using the int() method.
long
can 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With