Luke
Luke

Reputation: 15

How to convert a String to a float in Python 2.7

I am trying to convert decimal geographic coordinates as strings to a float. The coordinates are in a csv like this '51213512'. With my Python script I am just reading the coordinates and add the '.'. If I am not adding the comma the rest of my script isn't working.

I already tried a few things but nothing worked for me. This is what I got so far.

latitude=float(long('51.213512'))

The Result is a ValueError:

ValueError: invalid literal for long() with base 10: 'Long'

Upvotes: 1

Views: 1133

Answers (2)

m13op22
m13op22

Reputation: 2337

Get rid of the 'long' and it should work

latitude = float('51.213512')

Edit: Okay, since you're getting the coordinates and manually converting to decimal strings, all you need to do is use the code I said originally. The long function converts integers or strings of integers to long types, not float types.

>>> long(5)
5L
>>> long('5')
5L
>>> long(5.5)
5L
>>> long('5.5')
ValueError: invalid literal for long() with base 10: '5.5'

Upvotes: 1

user10993451
user10993451

Reputation:

not too sure why you are using long in this examply if you want to convert this variable to a float just use the float function on its own, you seem to be confusing the long and float functions. dont use both you will be confusing python (basically dosent know what to do because your giving it 2 arguments at once)

I recommend just using the float function on its own. This will avoid confusion

latitude = float('51.2135512')

Upvotes: 1

Related Questions