45

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 =)

2
  • 2
    convert it to float? Catch the error and report to the user? Commented Jan 24, 2011 at 2:12
  • 6
    This question and its answers only apply to Python 2. Python 3 no longer has a long type, see python3porting.com/differences.html#long Commented Dec 16, 2015 at 9:44

2 Answers 2

38

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

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

2 Comments

int('234.89') fails with the same error as shown in the question.
@payne- thanks for point out. I have corrected it. Your's was correct.
17

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

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.