Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert string to float error with negative numbers

How to convert a negative number stored as string to a float?

Am getting this error on Python 3.6 and don't know how to get over it.

>>> s = '–1123.04'
>>> float(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '–1123.04'
like image 488
PedroA Avatar asked Jul 23 '17 20:07

PedroA


People also ask

Can float take negative values in Python?

Float Data Type in Python Float represents floating point numbers in python. Decimal numbers or you can say real numbers are represented in python using double precision floating point numbers. A floating point number can be positive, negative or zero.

Why can't I convert a string to a float in Python?

The Python "ValueError: could not convert string to float" occurs when we pass a string that cannot be converted to a float (e.g. an empty string or one containing characters) to the float() class. To solve the error, remove all unnecessary characters from the string.

How do you make a negative float in Python?

In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number.

Can you convert string to float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.


2 Answers

Your string contains a unicode en-dash, not an ASCII hyphen. You could replace it:

>>> float('–1123.04'.replace('\U00002013', '-'))
-1123.04
like image 137
BrenBarn Avatar answered Nov 01 '22 05:11

BrenBarn


For a more generic solution, you can use regular expressions (regex) to replace all non-ascii characters with a hyphen.

import re

s = '–1123.04'

s = re.sub(r'[^\x00-\x7F]+','-', s)

s = float(s)
like image 1
user2589273 Avatar answered Nov 01 '22 06:11

user2589273